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

I have an array reference "$IpInfo". When I do data dumper it says:
$VAR1 = [ [ '20', '74', '6', '55', '56' ] ];
So you can see I have one array in my array reference.

When I do Data::Dumper of "$IpInfo->[0]" I get:
$VAR1 = [ '20', '74', '6', '55', '56' ];
And I try to assign my list to some scalars like:
my ( $id, $area, $cpu, $ip, $ip2 ) = $IpInfo->[0];
But when I:
print "$id, $area, $cpu, $ip, $ip2";
All I get is "ARRAY(0xb0e69dc), , , ,"

Why aren't my list elements being assigned to my scalars?

Replies are listed 'Best First'.
Re: Getting Specific List Elements Out of an Array Reference
by Zaxo (Archbishop) on Oct 31, 2005 at 05:55 UTC

    $IpInfo->[0] is an array reference - a single scalar. You need to dereference it to get a list of its elements.

    my ( $id, $area, $cpu, $ip, $ip2 ) = @{$IpInfo->[0]};
    Note that array elements and hash values are always single scalars. That will save you confusion.

    After Compline,
    Zaxo

      what would be done if @{$IpInfo->[0]} contain x number of elements and if we don't know what's x.

        If the dereferenced array were too short, the unspecified variables in the list would be declared but remain undefined. If too long, the extra values would be ignored by the program. That's a good reason to keep arrays arrays.

        After Compline,
        Zaxo

Re: Getting Specific List Elements Out of an Array Reference
by pg (Canon) on Oct 31, 2005 at 05:54 UTC
    my ( $id, $area, $cpu, $ip, $ip2 ) = @{$IpInfo->[0]};

    With what you did, you simply assigned $IpInfo->[0], an array ref to $id. You can prove this by:

    use Data::Dumper; use strict; use warnings; my $IpInfo = [ [ '20', '74', '6', '55', '56' ] ]; my ( $id, $area, $cpu, $ip, $ip2 ) = $IpInfo->[0]; print Dumper($id);

    Which prints:

    $VAR1 = [ '20', '74', '6', '55', '56' ];

    And that's what you got earlier when you tried to dump $IpInfo->[0].

Re: Getting Specific List Elements Out of an Array Reference
by Delusional (Beadle) on Oct 31, 2005 at 10:13 UTC
    Depending on how the data is, in $IpInfo, you might want to use split to break the data into elements to store in the scalars:
    Example
    my @IpInfo = qw{ 20,74,6,55,56 10,20,30,40,50 100,200,300,400,500 }; foreach my $element (@IpInfo) { my ( $id, $area, $cpu, $ip, $ip2 ) = split(/,/,$element); print "id: $id\tarea: $area\tcpu: $cpu\tip: $ip\tip: $ip2\n"; }
A reply falls below the community's threshold of quality. You may see it by logging in.