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

This is a very basic problem and I've tried many different ways to make this work. I've looked at References quick reference by tye, perlref and checked a few books, but can't find anything quite like my code.

This is the closest I have come, but I end up with a reference to an array instead of an array for @fields. I've used similar structures before but not exactly in this way:

use strict; use warnings; use Data::Dumper; my @fields; GetTables('ABC', \@fields); print Dumper(\@fields); sub GetTables { my ($table_name, $aref) = @_; my %tables = ( 'ABC' => [ qw( f1 f2 f3) ], 'DEF' => [ 'f1', 'f2' ], ); @$aref = $tables{$table_name}; ## originally I had the following, but it didn't work ## $aref = $tables{$table_name}; print Dumper(\%tables, $aref); }
The results look like this:
$VAR1 = { 'ABC' => [ 'f1', 'f2', 'f3' ], 'DEF' => [ 'f1', 'f2' ] }; $VAR2 = [ $VAR1->{'ABC'} ]; $VAR1 = [ [ 'f1', 'f2', 'f3' ] ];
The problem is, I want the last dump to be a plain array, which should look like the following:
$VAR1 = [ 'f1', 'f2', 'f3' ];
Can someone please show me where I've gone astray? Thanks.

Replies are listed 'Best First'.
Re: Referencing a HoA
by BrowserUk (Patriarch) on Jun 02, 2003 at 02:28 UTC

    Close. Change @$aref = $tables{$table_name};

    to  @$aref = @{ $tables{$table_name} };


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


      Thanks so much! I thought that I had already tried that... Oh well, hopefully now I can make good progress in the next 3-4 hours.
Re: Referencing a HoA
by educated_foo (Vicar) on Jun 02, 2003 at 02:34 UTC
    You want @$aref = @$tables{$table_name}; instead of
    @$aref = $tables{$table_name};
    As for why $aref = $tables{$table_name} doesn't work, it's because $aref is just a scalar value, so you're just changing the value of the lexical $aref, not @fields.

    /s

    Update: See replies -- I forgot the curlies around $tables{$table_name}.

      or would that be @$aref = @{$tables{$table_name}}; ?

      cheers,

      J

      That yields the following message:
      Global symbol "$tables" requires explicit package name at noname.pl li +ne 18. Execution of noname.pl aborted due to compilation errors.
      Though I thought it was the equivalent of what BrowserUk posted:
      @$aref = @{ $tables{$table_name} };
      which does work. I guess I need to study references more closely. :(