Jesse Lactin
Jesse Lactin

Reputation: 311

find duplicate filenames and append them to hash of arrays

Perl question: I have a colon separated file containing paths that I'm using. I just split using a regex, like this:

my %unique_import_hash;

while (my $line = <$log_fh>) {
    my ($log_type, $log_import_filename, $log_object_filename) 
        = split /:/, line;

    $log_type =~ s/^\s+|\s+$//g; # trim whitespace
    $log_import_filename =~ s/^\s+|\s+$//g; # trim whitespace
    $log_object_filename =~ s/^\s+|\s+$//g; # trim whitespace
}

The exact file format is:

type : source-filename : import-filename

What I want is an index file that contains the last pushed $log_object_filename for each unique key $log_import_filename, so, what I'm going to do in English/Perl pseudo-code is push the $log_object_filename onto an array indexed by the hash %unique_import_hash. Then, I want to iterate over the keys and pop the array referred by %unique_import_hash and store it in an array of scalars.

My specific question is: what is the syntax for appending to an array that is the value of a hash?

Upvotes: 1

Views: 84

Answers (3)

Matt Jacob
Matt Jacob

Reputation: 6553

If you only care about the last value for each key, you're over-thinking the problem. No need to fool around with arrays when a simple assignment will overwrite the previous value:

while (my $line = <$log_fh>) {
    # ...
    $unique_import_hash{$log_import_filename} = $log_object_filename;
}

Upvotes: 4

simlev
simlev

Reputation: 929

use strict;
use warnings;
my %unique_import_hash;

my $log_filename = "file.log";
open(my $log_fh, "<" . $log_filename);

while (my $line = <$log_fh>) {
    $line =~ s/ *: */:/g;
    (my $log_type, my $log_import_filename, my $log_object_filename) = split /:/, $line;
    push (@{$unique_import_hash{$log_import_filename}}, $log_object_filename);
}

Seek the wisdom of the Perl monks.

Upvotes: 2

choroba
choroba

Reputation: 241828

You can use push, but you have to dereference the array referenced by the hash value:

push @{ $hash{$key} }, $filename;

See perlref for details.

Upvotes: 4

Related Questions