On 9/17/09 Thu  Sep 17, 2009  12:41 PM, "Uri Guttman" <u...@stemsystems.com>
scribbled:

>>>>>> "SB" == Steve Bertrand <st...@ibctech.ca> writes:
> 
> 
>   SB> while ( my $entry = <DATA> ) {
> 
>   SB>     my ( $router, $ip ) = split /\s+/, $entry;
> 
>   SB>     next if ! defined $ip;
> 
> how would $ip not be defined if the split works? a simpler boolean test
> is likely all that is needed. also unless is cleaner
> IMO:

Let's be accurate and complete: $ip will be undefined if there are no spaces
in $entry. That is probably what you mean by the split not working? Some
would say the split is working in that case, just not returning two defined
values.

> 
> next unless $ip

That will reject an entry with $ip = '0', whereas the test for defined $ip
will not, so there is a difference. While not a good IP address, you do want
to be careful in the general case.

Another approach for parsing the file and saving the results is to use an
array of arrays:

    my @records;
    while(<DATA>) {
        push( @records, [ split ] );
    }

This has the advantage of maintaining order of the entries and using less
storage than anything using a hash. For only two values per entry, it is
easy enough to remember what the values are:

    for ( @records ) {
        my( $hostname, $ip ) = @$_;
        ...
    }

I typically use this method for anything up to 8-10 entries. However, more
than 3 is probably not recommended.

If you have to look up the data by hostname, then a hash might be better.
But if you have only to traverse over the entries, an array will suffice in
many cases.

If your hosts have multiple addresses, then you can use a hash of arrays to
keep the multiple addresses:

    my %hosts;
    while(<DATA>) {
        my( $host, $ip ) = split;
        push( @{$hosts{$host}}, $ip );
    }

This will not overwrite any data. You will probably have many one-element
arrays, however.

-- 
Jim Gibson



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to