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

I have a program set up to run through a file containing a list of tests to run, with some of the tests in different folders. I want to set up an array of hashes to do this. Here's how I have it set up:
my $test_list = "some_tests"; open TESTS, $test_list or die "Can't open $test_list: $!\n"; my @tests; while (<TESTS>) { my %tests; next if /^\s*$/; my $temp = $_; if ($_ =~ /\//) { $temp =~ s/\/.*//; chomp $temp; s/.*\///; } else { $temp = "*"; } chomp; $tests{$_} = $temp; push @tests, %tests; } close TESTS; my $count = 0; for (@tests) { $count++; my %tests = $_; my ($test, $category) = each %tests; print "Starting $test... ($count/@{[scalar @tests]})\n"; print "Test: " . $test . "\n"; print "Category: " . $category . "\n"; }
I can't quite seem to get this working properly, though. I've tried using each directly on $_, as well, with no success. It seems to work fine up until the point that it tries to print out $category. Perl gives me a warning that it has not been initialised. I've checked Perldoc and searched through SOPW, and found precious little information on arrays of hashes. If anyone could help, I'd be most appreciative. I'm running Perl 5.8.0 on Irix 6.5

Replies are listed 'Best First'.
Re: Using an array of hashes
by Zaxo (Archbishop) on Oct 25, 2002 at 04:58 UTC

    The value in an array or hash must be a scalar, so what we call an AoH is really an array of references to hashes. Your line 19, push @tests, %tests; puts %tests into list context and pushes each key and value onto the top level array seperately, leaving no means of distinguishing the individual hashes. Change that line to:         push @tests, \%tests;

    After Compline,
    Zaxo

Re: Using an array of hashes
by grep (Monsignor) on Oct 25, 2002 at 05:03 UTC

    You need to store a reference in your array else you will flatten your hash

    change
    push @tests, %tests;
    to
    push @tests, \%tests;

    Then you want to dereference

    change
    my %tests = $_;
    to
    my %tests = %$_



    grep
    Mynd you, mønk bites Kan be pretti nasti...
      Cool. I changed both of the lines, and now the code works perfectly. Thanks a whole bunch!
Re: Using an array of hashes
by jdporter (Paladin) on Oct 25, 2002 at 15:48 UTC
    I have a question.

    If an input line consists of a text with no slash, say, "foo", then, based on the output of your script (above, + the fix suggested by grep) the name of the test is "foo" and the category is "*". Is that what you intended?