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

Hi,
I have a data file which contains a hash of arrays.
(The purpose of which is to lookup allowed columns to search my database by)
sort.pl
{ 0 => ['price'], 23 => ['brightness', 'resolution', 'weight'], }


I can access this data with the following code:
use strict; my $sort; unless ($sort = do ('G4 HD:Desktop Folder:sort.pl')) { die ("Could not open config file"); } print $sort->{23}[0];
Which returns brightness
What I wish to do is search through one of the arrays to check if it contains a particular value.
If I do
print $sort->{23};
I get
ARRAY(0x2b9a4388)
but I don't know how to dereference this.

What I'd like to do is something like this,
my $search = 'price'; my $column = 23; foreach ($sort->{$column}) { #(search each indices for $search) }

Replies are listed 'Best First'.
Re: Dereferencing a hash reference to a Hash of Arrays
by Abigail-II (Bishop) on Jun 19, 2002 at 11:31 UTC
    The rule in Perl is simple. Where every you write $variable, @variable, %variable, &variable or *variable, you may replace variable with a block whose value is a reference of the appropriate type.

    So, in your case, you want to write something like

    foreach (@array) { ... }
    but you don't have an array, just a reference to one ($sort -> {column} being the reference). So, you would write:
    foreach (@{$sort -> {column}}) { ... }

    Abigail

Re: Dereferencing a hash reference to a Hash of Arrays
by jmcnamara (Monsignor) on Jun 19, 2002 at 10:14 UTC

    You can dereference the array ref like this:     @{$sort->{23}};

    To check if a certain column contains a certain value you could do something like this:     my $found = grep {/^$search$/}  @{$sort->{$column}};

    --
    John.

Re: Dereferencing a hash reference to a Hash of Arrays
by Chmrr (Vicar) on Jun 19, 2002 at 10:08 UTC

    You want to use @{...} to dereference the array reference. That is, @{$sort->{23}} will get you a list. For your specific problem, I'd do:

    my $search = 'price'; my $column = 23; if (grep {$_ eq $search} @{$sort->{$column}}) { # ... }

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

(tye)Re: Dereferencing a hash reference to a Hash of Arrays
by tye (Sage) on Jun 19, 2002 at 16:06 UTC

    Nearly this exact question gets asked quite frequently around here. I find that References Quick Reference makes the rules of dereferencing Perl data structure references very easy to remember, so I mention it every so often when this question comes up.

            - tye (but my friends call me "Tye")
Re: Dereferencing a hash reference to a Hash of Arrays
by DamnDirtyApe (Curate) on Jun 19, 2002 at 13:44 UTC