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

I am returning a reference to an array a scalar and 2 references to hashes
I then pass these values to different subroutines.
How do I loop through the values of the hashes.
below is the code that passes returns the values
my($dbh) = @_; my @datamodels; my %filenames; my %dbids; my $sql = "select DATAMODEL_CD, DB_ID, FILENAME from PRDRELEASE wh +ere RELEASE_FG = 1"; my $sth = $$dbh->prepare($sql) or $app->error($FATAL, "Can't do SQL statement [ $sql ] :: +$DBI::errstr"); $sth->execute(); while (my @values = $sth->fetchrow_array()){ push (@datamodels, $values[0]); $dbids{$values[0]} = $values[1]; $filenames{$values[0]} = $values[2]; }#end while loop printf("@datamodels\n"); my $numelements = @datamodels; return (\@datamodels, $numelements, \%dbids, \%filenames);

This is the code recieving the the values from the above code
my ($datamodels, $numelements, $dbids, $filenames) = get_data(\$dbh);

Now I pass filenames to a different subroutine.
create_file(\$dbh, $datamodels, $date, $numelements, $filenames);

How do I call the appropriate value within the calling subroutine?
This is what I have tried.
my ($dbh, $datamodel, $date, $numelements, $filenames) = @_; my $file = "$filenames{$datamodel->[$count]}" print "$file\n";

Replies are listed 'Best First'.
Re: Returning and passing references to hashes
by ikegami (Patriarch) on Jan 04, 2006 at 18:48 UTC

    You're treating "filenames" as a hash
    $filenames{...}
    instead of a reference to a hash
    $filenames->{...}
    or
    ${$filenames}{...}

    In other words,
    my $file = "$filenames{$datamodel->[$count]}";
    should be
    my $file = $filenames->{$datamodels->[$count]};
    (What's with the quotes?)

    Update: ... except that $count is undefined. Maybe you want

    foreach my $datamodel (@$datamodels) { my $file = $filenames->{$datamodel}; print "$file\n"; }
    You could also do away with $datamodels entirely, but the order of the output would be random.
    foreach my $datamodel (keys %$filenames) { my $file = $filenames->{$datamodel}; print "$file\n"; }

    I'd get rid of $numelements. There's no use for it.

    Update: Some PerlMonks references on references:
    Dereferencing Syntax
    References Quick Reference
    References Tutorial

       my $file = $filenames->{$datamodel}; this will work.
      the quotes were just a mistake.
      Now that I can reference it this way I will get rid of numelements.
      I will keep those references in my favorites thank you.
Re: Returning and passing references to hashes
by Roy Johnson (Monsignor) on Jan 04, 2006 at 18:37 UTC
    See perldoc perlreftut about using references.

    If you have hashrefs in scalar variables (as you do, e.g., $dbids), you can loop through the values like so:

    for my $val (values %$dbids) { # Do something with a value...

    Caution: Contents may have been coded under pressure.