how to assign lines of variable length to a variable in perl?
hash, perl
Solution
This should do what you want.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
open my $loclist, '<', "test.txt" or die $!;
my %locs;
while (<$loclist>) {
my ($loclist_loc, @loclist_rec) = split;
$locs{$loclist_loc} = \@loclist_rec;
}
print Dumper \%locs;
OUTPUT:
$ perl test.pl
$VAR1 = {
'loc2' => [
'id2'
],
'loc1' => [
'id1',
'id4',
'id5',
'id9'
],
'loc3' => [
'id1',
'id11',
'id23'
]
};
Problem
I have a file I want to read that has a variable number of ids for each location that looks like this: ``` loc1 id1 id4 id5 id9 loc2 id2 loc3 id1 id11 id23 ``` I would like to store this as follows locs(loc) = {all ids belonging to that location} So that later, when I read another file I can do something like ``` if (grep id, locs(loc)){do something} ``` I tried to do this using a hash, but this is not working. I tried: ``` open my $loclist, '<', $ARGV[0]; my %locs; while (<$loclist>) { my @loclist_rec = split; my $loclist_loc = @rlist_rec[0]; $locs{$loclist_loc} = @loclist_rec; } ``` but this isnt working. I new to perl and still trying to understand the different datatypes. Any ideas? Thanks a lot!