in reply to Re: Help with sorting/randomizing?
in thread Help with sorting/randomizing?

Thank you Grandfather. I don't really know where to start or how to start really. This is beyond me. If someone could show me a bit of code, I think I can pick up from there. I know what perlmonks is, I have often turned here for help in the past. But this issue I am not able to solve, and I thought someone experienced here could give me a hand (for a donation, or whatever). Thanks. J

Replies are listed 'Best First'.
Re^3: Help with sorting/randomizing?
by GrandFather (Saint) on Mar 25, 2012 at 20:19 UTC

    In your OP you say "All my attempts have been futile." which implies you have attempted a solution. Show us your last attempt and describe the problem you had with it.

    Did I say PerlMonks isn't a code writing service?

    Welcome along to PerlMonks by the. Were you here before as an Anonymous Monk, or have you gotten yourself a new name?

    True laziness is hard work
      while($line = <$in_fh>) { chomp $line; if ($line =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)/) { $a = $1; $b = $2; $c = $3; $d = $4; $ip = "$a.$b.$c.$d"; $classc = "$a.$b.$c"; } next unless defined $ip; push @{ $ips{$classc} }, $ip; } foreach $classc (sort keys %ips) { print $ips{$classc}[rand @{$ips{$classc}}] . "\n"; }

        A problem with the above is that after the first valid IP address has been defined, there is nothing that explicitly undefines it, so the following line becomes useless:

        next unless defined $ip;

        The minimal change you could make to fix this bug would be to add $ip = $classc = undef; just before the if block.

        You could improve it further by use strict combined with putting a bit of thought into the scoping of variables.

        It can be reduced to:

        use 5.010; use strict; use warnings; my %ips; while (<$in_fh>) { if (/^(\d+)\.(\d+)\.(\d+)\.(\d+)/) { my $ip = "$1.$2.$3.$4"; my $classc = "$1.$2.$3"; push @{ $ips{$classc} }, $ip; } } foreach my $classc (sort keys %ips) { say $ips{$classc}[rand @{$ips{$classc}}]; }

        Personally I'd go further and reduce it even more. This might be a little too terse for some people's tastes though...

        use 5.010; use strict; use warnings; my %ips; while (<$in_fh>) { push @{ $ips{"$1.$2.$3"} }, "$1.$2.$3.$4" if /^(\d+)\.(\d+)\.(\d+)\.(\d+)/; } say $ips{$_}[rand @{$ips{$_}}] for sort keys %ips;
        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      Code I pasted does not show.