1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#!/usr/bin/perl use warnings; use strict; sub getIPasNumber { my $l = shift; chomp($l); my @a = split(" ", $l); my $n = $a[2]; $n =~ s/\.//g; return $n; } my @a = ("Server 1 111.222.333.444", "Server 2 222.333.444.555", "Server 3 111.333.444.555"); my %h; my $i; foreach $i (@a) { my $num = getIPasNumber($i); $h{$num} = $i; } foreach $i (sort {$b <=> $a} (keys(%h))) { print "$h{$i}\n"; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
... ### open read only; using lexical filehandle and three-argument-open open my $filehandle, '<', $filename or die "open($filename,ro) failed: $!"; ### read linewise from filehandle while ( my $line = <$filehandle> ) { ## work with $line } ### close filehandle close $filehandle; ...
Quote10.0.0.0
70.0.0.0
10.0.0.00
1.222.222.222
1 2 3 4 5 6
sub ipToInt { my $ip = shift; my $sum = 0; $sum = $sum*256 + $_ for split/\./, $ip; return $sum }
1 2 3 4 5
@sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, ipToInt((split " ",$_)[-1])] } @unsorted;
2015-03-20T19:46:26 RaubtierWas ist daran jetzt schwierig?
Mit meiner ipToInt-Funktion oben:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#!/usr/bin/perl use warnings; use strict; my $filename = "test"; sub ipToInt { my $ip = shift; my $sum = 0; # Splitting at dots is tricky: my @arr = split('\.', $ip); my $i; foreach $i (@arr) { $sum = $sum * 256 + $i; } return $sum; } sub getIPasNumber { my $l = shift; chomp($l); my @a = split(" ", $l); return ipToInt($a[2]); } my $fh; open($fh, "<", $filename) or die; my @a = <$fh>; close $fh; my %h; my $i; foreach $i (@a) { chomp($i); my $num = getIPasNumber($i); $h{$num} = $i; } foreach $i (sort {$b <=> $a} (keys(%h))) { print "$h{$i}\n"; }