Mihir
Mihir

Reputation: 557

Perl loop through hash of arrays

How can i loop each element in first line and then move to second line and so on.. Below script is somewhat working, but i'm not getting desired output. Can someone please help me.

test.txt

ABC-13077 817266 55555
ABC-13092 816933
CAMC-13093 817361

script.pl

#!/usr/bin/perl -w
use strict;

my %hash = ();
my $file = "test.txt";

open (my $fh, "<", $file) or die "Can't open the file $file: ";

while (my $line =<$fh>)
{
    chomp ($line);
    my($key) = split(/\+s/, $line);
    $hash{$key} = 1;
}

foreach my $key (keys %hash)
{
    print "$key\n";
    print "loop\n";
}

current output.txt

ABC-13077 817266 55555
loop
ABC-13092 816933
loop    
CAMC-13093 817361

desired output.txt

ABC-13077
817266 
55555
loop
ABC-13092 
816933
loop    
CAMC-13093 
817361

Upvotes: 2

Views: 244

Answers (1)

toolic
toolic

Reputation: 61937

Firstly, you need to change /\+s/ to /\s+/.

Secondly, you could store your data into a hash-of-arrays (perldsc):

use warnings;
use strict;
my %hash = ();

while (my $line =<DATA>)
{
    chomp ($line);
    my ($key, @vals) = split(/\s+/, $line);
    $hash{$key} = [@vals];
}

foreach my $key (sort keys %hash)
{
    print "$key\n";
    print "$_\n" for @{ $hash{$key} };
    print "loop\n";
}

__DATA__
ABC-13077 817266 55555
ABC-13092 816933
CAMC-13093 817361

Output:

ABC-13077
817266
55555
loop
ABC-13092
816933
loop
CAMC-13093
817361
loop

Upvotes: 1

Related Questions