dru145 has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I have the following code (*note: IP's have been changed):
splice(@ips, 15); for $i ( 0 .. $#ips ) { print "\t $i is @{$ips[$i]},\n"; } Output: number 0 is 192.168.36.118 12431 46.08%, number 1 is 192.168.80.103 4203 1.56%, number 2 is 192.119.15.61 3627 1.34%, number 3 is 192.19.125.2 1738 0.64%, number 4 is 192.217.1.21 1134 0.42%, number 5 is 192.17.214.10 852 0.32%, number 6 is 192.2.252.1.768 0.28%, number 7 is 192.134.77.97 498 0.18%, number 8 is 192.8.29.90 489 0.18%, number 9 is 192.11.7.17 409 0.15%, number 10 is 192.10.191.29 394 0.15%, number 11 is 192.247.91.18 25 0.09%, number 12 is 192.229.14.7 231 0.09%, number 13 is 192.131.192.206 227 0.08%, number 14 is 192.161.31.247 172 0.06%,

I want to add the first (ip address) and second (number of attempts) columns to their own array. I was able to add the first column with this code:
my @newips = (); my ($x, $y); $y = 0; for ($x = 0; $x < 15; $x++) { push @newips, $ips[$x][$y] }
then I tried to add the second column with this code:
my @num = (); $x = 0; for ($y = 0; $y < 15; $y++) { push @num, $ips[$x][$y] }
Which only prints:   192.168.36.118 12431  46.08%

What is the best way to do this? I read perllol which got me this far, but now I'm stuck.

Thanks,
Dru

Replies are listed 'Best First'.
Re: Array of Arrays Question
by Masem (Monsignor) on Dec 21, 2001 at 02:45 UTC
    You're close; your second bit of code is changing the wrong index. You want:
    #original (for the 1st column): $y = 0; for ($x = 0; $x < 15; $x++) { push @newips, $ips[$x][$y]; } #new code, gets the second column $y = 1; for ($x = 0; $x < 15; $x++) { push @num, $ips[$x][$y]; }
    Of course, you can simplify this by:
    for ($x = 0; $x < 15; $x++) { push @newips, $ips[$x][0]; push @num, $ips[$x][1]; }
    (And there's many other optimizations/simplifications that could be done as well, but probably not worth going into at this time).

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    "I can see my house from here!"
    It's not what you know, but knowing how to find it if you don't know that's important

Re: Array of Arrays Question
by indapa (Monk) on Dec 21, 2001 at 03:32 UTC
    The previous posts have answered your question, in the future you may find visualizing nested data structures with Data::Dumper helpful when trying debug them.
Re: Array of Arrays Question
by Zaxo (Archbishop) on Dec 21, 2001 at 02:57 UTC

    You need to split on whitespace. Here is one way:

    # convert @ips to AoA # oops already is # @ips = map { [split " "] } @ips; my @newips = map { $_->[0] } @ips; my @num = map { $_->[1] } @ips;

    Update: Oops, misread. The maps stand.

    After Compline,
    Zaxo