Canonicalize CIDR: Difference between revisions

→‎{{header|Raku}}: Add implementation.
(→‎{{header|Raku}}: Add implementation.)
Line 64:
{{Out}}
<pre>$ canonicalize_cidr.py 87.70.141.1/22
87.70.140.0/22</pre>
=={{header|Raku}}==
{{trans|Perl}}
<lang raku>#!/usr/bin/env raku
 
# canonicalize a CIDR block: make sure none of the host bits are set
if (!@*ARGS) {
@*ARGS = $*IN.lines;
}
 
for @*ARGS -> $cidr {
# dotted-decimal / bits in network part
my ($dotted, $size) = $cidr.split('/');
 
# get IP as binary string
my $binary = ($dotted.split('.').map: { sprintf "%08b", $_ }).join;
 
# Replace the host part with all zeroes
$binary.substr-rw($size) = "0" x (32 - $size);
 
# Convert back to dotted-decimal
my $canon = ($binary.comb.batch(8).map: { .join.parse-base(2) }).join('.');
 
# And output
say "$canon/$size";
}</lang>
 
{{Out}}
<pre>$ canonicalize_cidr.raku 87.70.141.1/22
87.70.140.0/22</pre>
1,481

edits