in reply to comparing list to 2 cells in array

As best as I can understand, you are trying to do the following: check a list of IP addresses (IPs.txt) against a list of IP address ranges (provided in source.txt), and print each address in the list of IP addresses, along with a region if the address matched a range.

Going on this premise, I've rewritten most of your code to do just that. The big problems with your existing code are as follows:

Here is the code, rewritten to comply with the guidelines I listed, and intended to accomplish the goal I guessed you're trying for.

source.txt
123.123.123.123 124.124.124.124 Canada BC 111.111.111.111 112.112.112.112 Canada AB 11.11.11.11 12.12.12.12 USA WA 22.22.22.22 23.23.23.23 USA OR 33.33.33.33 34.34.34.34 USA CA
IPs.txt
10.10.10.10 11.11.12.12 123.123.122.122 123.123.124.125
Perl program
#!perl # use strict ; use warnings ; open INFO, 'IPs.txt' or die $! ; chomp( my @IPs = <INFO> ) ; close INFO ; my @rows = () ; open IN, ' source.txt' or die $! ; while (<IN>) { next if /^$/ ; my %table = () ; @table{ 'ip', 'ip2', 'country', 'region' } = split ; $table{ 'num_ip' } = sprintf '%03d' x 4, split /\./, $table{ 'ip' + } ; $table{ 'num_ip2' } = sprintf '%03d' x 4, split /\./, $table{ 'ip2 +' } ; push @rows, \%table ; } close IN; open OUT, '>>conversion.txt' or die $! ; foreach my $ip ( @IPs ) { my $match = 0 ; my $num_ip = sprintf '%03d' x 4, split /\./, $ip ; foreach my $row ( @rows ) { if ( $num_ip >= $row->{'num_ip'} && $num_ip <= $row->{'num_ip2 +'} ) { printf OUT "%-16s %s\n", $ip, $row->{'region'} ; $match++ ; } } printf OUT "%-16s\n", $ip if !$match ; } close OUT;
Output
10.10.10.10 11.11.12.12 WA 123.123.122.122 123.123.124.125 BC

Let me know how close to the mark this is.


_______________
D a m n D i r t y A p e
Home Node | Email

Replies are listed 'Best First'.
Re: Re: comparing list to 2 cells in array
by Anonymous Monk on Jul 26, 2002 at 19:21 UTC
    This seems like it would work very well. I have ran it, and I'm getting an error "%table requires a specific package name". I looked this up, and so I know that it is because I'm using "Use Strict" and I need to declare something. I saw someone about declaring vars, defs, and something else, but didn't understand it. So can I just declare %table to get it to work? I looked at it, and normally my %table should work, because it is local, but, the code didn't like it anyway. Thanks, Carrie

      What OS/Perl version are you running? This works fine for me on RH7.3, with Perl 5.6.1.


      _______________
      D a m n D i r t y A p e
      Home Node | Email
        Its Perl v5.6.1, but on Windows2000 Standard server.

      Actually, you declared a hash %table and used an array @table.

      Update: my fault. I just learned that you can write things like @table{ 'ip', 'ip2', 'country', 'region' } = split ;