in reply to Re: Fill Arbitrary Array
in thread Fill array

I don't know which arrays are filled with this code :(
sub fill_array(\@) { my ($right_array) = @_; # ... while (my @row = $sth->fetchrow_array()) { push (@$right_array, \@row); } print "Values: @$right_array\n"; #Works! } fill_array(@name); foreach my $entry (@name) { print "$entry\n"; #Remains empty... }

Replies are listed 'Best First'.
Re^3: Fill Arbitrary Array
by tadman (Prior) on May 02, 2002 at 17:22 UTC
    It should fill whatever array you pass to it, which in this case is @name. The reason this can be done is because of the way the sub is declared, in particular, the (\@) definition means that the first parameter is an array reference. This way, instead of passing a copy of the @name array, a reference to it is passed, allowing you to manipulate it.

    With that in mind, I'm surprised that you get "nothing". @name should be filled with array references, these sub-arrays that contain the various rows. Using your code, since you are not de-referencing them, you should see something like this:
    ARRAY(0x80fe5a8) ARRAY(0x80fe5d2) ARRAY(0x80fe6f4)
    The reason is you are printing an array reference as a string, which isn't going to work. A solution is to either use the venerable Data::Dumper or just deference it:
    # Data::Dumper saves the day again use Data::Dumper; print Dumper (\@name); # De-reference it and treat it as an array foreach my $row (@name) { print join (',', @$row),"\n"; }
    I'm not sure how familiar you are with references, but here's a 5 second intro:
    my @array = qw[ 1 2 3 ]; my $array_ref = \@array; # Backslash makes a reference my @array_copy = @$array_ref; # @ de-references array reference $array[2] = 4; # Modifies @array directly print $array_ref->[2]; # Should be '4' now $array_ref->[1] = 5; # Modifies @array by reference print $array[1]; # Should be '5' $array_copy[1] = 6; # Modifies @array_copy, not @array print $array[1]; # Still '5'