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

I have a table that produces the following results:

DIR FILE_NAME | 954 | 24088954 | | 955 | 24052955 | | 955 | 24111955 | | 955 | 24130955 | | 956 | 23159956 | | 957 | 24133957 | | 958 | 24131958 | | 960 | 24093960 | | 961 | 24033961 | | 961 | 24129961 | | 961 | 24130961 |

I am trying to create a hash of these values based on the directory:

955 -> 24052955, 24111955, 24130955
961 -> 24033961, 24122961, 24130961

I am guessing that I need to hash the directory, but then have an array as the value of the hash

The problem I have is that when I did
$file_hash->{$dir}{push(@file_array,$file_name)};

I get duplicates
foreach my $file_dir (sort (keys % {$file_hash})) { foreach my $file (@file_array){ print "$counter Directory: $file_dir $file\n"; $counter++; + } + } 1 Directory: 000 24090000 2 Directory: 000 24125002 3 Directory: 000 24011003 4 Directory: 000 24070003 5 Directory: 000 24082003 6 Directory: 000 24065005 7 Directory: 000 24070007 8 Directory: 000 24132007 9 Directory: 000 24041008
As you can see, the second record here doesn't belong (the last three digits of the file name correspond to the directory).

So it would seem that I need to pre-define 1000 different arrays, one for each directory, and then do an if statement to push the values into the approriate array,but I am sure there is a better way to handle this.

Replies are listed 'Best First'.
Re: hash or arrays
by cLive ;-) (Prior) on Oct 03, 2004 at 19:28 UTC
    Nearly there:
    push @{ $file_hash->{$dir} },$file_name; foreach my $file_dir (sort keys %{$file_hash}) { foreach my $file (@{ $file_hash->{$dir} }) { print "$counter Directory: $file_dir $file\n"; } }
    cLive ;-)
      This is beautiful. Works like a champ. Greatly appreciated.
Re: hash or arrays
by Arunbear (Prior) on Oct 03, 2004 at 19:27 UTC
    Given $file_hash, $dir and $file_name, do the insertion like this:

    push @{ $file_hash->{$dir} }, $file_name;

    The arrays that $file_name are pushed into will be created automagically by Perl.

    Then to create the report:

    foreach my $file_dir (sort keys %{$file_hash}) { foreach my $file (@{ $file_hash->{$file_dir} }){ print "$counter Directory: $file_dir $file\n"; $counter++; } }