Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Sorry Monks , but can someone tell me what is wrong with this code ?
my %lineFileContains; my @r = (); open my $fh, "ZaaFile" or die "open failed: $!"; my $line; while ($line = <$fh>) { chomp (@r = split/\s+/); push @{$lineFileContains{$r[3]}}, [@r[4..$#r]]; } close $fh; foreach (reverse sort keys %lineFileContains) { print "$_"; foreach (@{$lineFileContains{$_}}) { print "\t$_->[3]\t$_->[4]\n"; } } data ---- A 234453234324 Hlell Sam Two
my data file contains lots of lines similar to the one at the top , what I need is to get the last two words in each line and print them , in the case above , my output should be
Sam Two
Not sure if it is my hash or my print statment. thanks

Replies are listed 'Best First'.
Re: values of hash table
by esskar (Deacon) on Mar 04, 2004 at 05:57 UTC
    what about
    push @{$lineFileContains{$r[3]}}, [@r[3..$#r]];
    and
    foreach (@{$lineFileContains{$_}}) { print "\t$_->[0]\t$_->[1]\n"; }
    and

    are you sure about
    push @{$lineFileContains{$r[3]}},
    or should it be
    push @{$lineFileContains{$r[2]}},
    ???
Re: values of hash table
by Anonymous Monk on Mar 04, 2004 at 06:16 UTC
    Several Problems:

    while ($line = <$fh>) { chomp (@r = split/\s+/);

    You read into $line, but you are split()'ing $_ (and you'll probably want to use the special case split: split " ", $line.

    push @{$lineFileContains{$r[3]}}, [@r[4..$#r]];

    Your indices seem a little too high to be grabbing the last two elements from a 5 element list (ie, [4] is the last index)

    foreach (@{$lineFileContains{$_}}) { print "\t$_->[3]\t$_->[4]\n"; }

    If the array you pushed onto your hash was only supposed to have two elements, why are you trying to access the 4th and 5th elements in the array?

Re: values of hash table
by TomDLux (Vicar) on Mar 04, 2004 at 18:25 UTC

    Whether you use " " or \s+/ with the split, you don't need chomp.

    On the other hand, if you want to use it, for clarity, the appropriate usage would be to chomp the lines as they are read in:

    while ( $line = <$fh> ) { chomp $line; @r = split " ", $line; .....

    --
    TTTATCGGTCGTTATATAGATGTTTGCA