in reply to hash help

I think this looks pretty close...
#!/usr/bin/perl -w use strict; my @files = qw(file1.dat file2.dat); my %hash; foreach my $file (@files) { open (FILE, "<", $file) || die "can't open $file $!"; while (<FILE>) { next if /^\s*$/; chomp; my ($name,@tokens) = split(/,/,$_); $name =~ s/_.*$//; #delete trailing _blah in name push @{$hash{$name}},@tokens; } } foreach my $name (sort keys %hash) { print "$name @{$hash{$name}}\n"; } __END__ prints: Bbbb 3333 4444 23 45 Cdd 3444 3444 24.45 Zddd 345 456 34 456.4 file1.dat: Bbbb,3333,4444 Cdd,3444,3444 Zddd,345,456 file2.dat Bbbb_rf1,23,45 Cdd_rf2,24.45 Zddd,34,456.4

Replies are listed 'Best First'.
Re^2: hash help
by bkish11 (Novice) on Jun 30, 2009 at 01:41 UTC

    Appericate your help, it worked some extended,thanks to that. May be I haven't explain too well

    Some of the input are concatenating and trimmed,I would say the first file (P1) and first field will be uniqe and in the second file (S1) "_ref1 or _ref3 or _ref4" will have extension.

    Input File One P1

    bbb,2,3

    aaa_1,4,5

    ccc_1,5,6

    Input file Two s1

    bbb_ref1,5

    aaa_1_ref3,8

    ccc_1_ref2,6

    Input file three S2 and S3

    bbb_ref1,10

    aaa_1_ref3,9

    ccc_1_ref2,11

    The result will be

    bbb,2,3,5,10

    aaa_1,4,5,8,9

    ccc_1,5,6,6,11

    I apologize for the confusion

      All that is required is a very slight "tweak" to the $name regex statement (if name ends in _refX, then that part is deleted, otherwise not).

      I suppose you are new to Perl. Note that one of the true "Powerhitter" feature of Perl is the total absence of indices (no [$i] stuff). The only "if" statement is pretty much optional provided that you have good data file to work with as it only skips completely blank lines. Play with the code. You will also notice that the order of the files doesn't matter (no special case for the first file).

      Have fun and happy Perling!

      #!/usr/bin/perl -w use strict; my @files = qw(file1.dat file2.dat file3.dat); my %hash; foreach my $file (@files) { open (FILE, "<", $file) || die "can't open $file $!"; while (<FILE>) { next if /^\s*$/; #simply skips blank lines chomp; my ($name,@tokens) = split(/,/,$_); $name =~ s/_ref\d+$//; push @{$hash{$name}},@tokens; } } foreach my $name (sort keys %hash) { print "$name @{$hash{$name}}\n"; } __END__ prints: aaa_1 4 5 8 9 bbb 2 3 5 10 ccc_1 5 6 6 11

        thanks for the help, I have one more questions, how would you process each vaules in hash of array, like I want add 5+8+9 then add to push to aaa_1 4 5 8 9 22

        can you just breif me how does it get popualted into single hash

        thanks it worked for me,I understand the tweaking part,still not clear how is it exactly matching with first field with all the three files. yes I have start learning perl very recently, thanks once again