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'

In reply to Re^5: Help with sorting/randomizing? by tobyink
in thread Help with sorting/randomizing? by countingcrows

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.