0

I am trying to create hash of arrays. I am taking data from a txt file and converting this into hash of arrays.

Txt file data is as below

group1 : usr1 usr4 usr6
group2 : usr2 usr1 usr5
group3 : usr1 usr2 usr3

so on ......

I am converting this hash of arrays like

%hash = (group1 => [usr1 usr4 usr6], group2 => [usr2 usr1 usr5]);

Following code i am trying

%hash = ();
open (FH, "2.txt") or die "file not found";
while (<FH>) {
@array = split (":", $_);
$array[1] =~ s/^\s*//;
$array[1] =~ s/\s*$//;
@arrayRef = split (" ", $array[1]);
$hash{$array[0]} = [ @arrayRef ];
#print @array;
#print "\n";
}
close FH;


print $hash{group1}[0];
print @{ $hash{group2}};

I am not getting output. There is something wrong in the code. Please help me understanding it better

2
  • split "" will split on the empty string, which means usr1 will be split up into qw(u s r 1). Commented Aug 12, 2013 at 10:05
  • Oh my mistake.. I corrected but not getting the output Commented Aug 12, 2013 at 10:10

2 Answers 2

3

Your code works for me, but the problem is that you are using the key "group1 " (note the extra space), and not "group1" like you think. When you split on colon :, you remember to strip the fields after from spaces, but not the field before. You should probably do:

my @array = split /\s*:\s*/, $_;

Also, you should always use

use strict;
use warnings;

Coding without these two pragmas is difficult and takes much longer.

Sign up to request clarification or add additional context in comments.

Comments

1
use strict;
use warnings;

my %hash;
open (my $FH, "<", "2.txt") or die $!;
while (<$FH>) {
  my ($key, @array) = split /[:\s]+/, $_;
  $hash{$key} = \@array;
}
close $FH;

use Data::Dumper;
print Dumper \%hash;

4 Comments

@Nitesh insted of $hash{$array[0]} = [ @arrayRef ]; you need my $key= shift @array;$hash{$key} = \@array; but since @array isn't lexicaly scoped (and it should be) that would be $hash{$key} = [ @array ];
How is it making difference. shift @array will give the last element which is index 1.
shift gives first element of array (array index starts with 0)
@mpapec No, his code is correct. The problem is the key is something other than he thinks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.