in reply to How do I re-read a line?

At the risk of posting code that you possibly can't use, how about a completely different approach. Instead of storing the names in one array and the items in other, how about creating a data structure that is a List of Hashes (LOH). Each hash has a 'name' key that points to a scalar, and an 'item' key that points to an array reference. Now you have a usuable data structure.

The idea is to store the names and the items into the hash, and when a new record is read, simply store the hash. The problem is that you have (well, i have to - this is an invitation for a more elegant solution should someone wish to show me a new trick ;)) discard the first line and store the last record outside of the while loop:

use strict; use Data::Dumper; my (@record, $discard, %temp); open(FH, 'data') or die 'file not found'; # discard the first line $discard = <FH>; while(<FH>) { chomp; s/\cM//; if (/^\d-RECORD$/) { push @record, {%temp}; undef %temp; } elsif (/ITEMNAME-(.*)/) { $temp{name} = $1; } elsif (/ITEM \d-(.*)/) { push @{$temp{item}}, $1; } } # the last record needs to be added outside while loop push @record, {%temp}; print Dumper \@record; # print items of last record print join(', ', @{$record[-1]{item}}), "\n";
If someone knows of a more elegant way, please share. I tried using File::ReadBackwards, but then extra work is needed to reverse the items ...

UPDATE:
Regarding your regexes - you might want to consider changing \d to \d+ so that you can catch numbers greater than 9, and you probably should use \s or \s+ instead of a literal space.

UPDATE: UPDATE:
Thanks belg4mit!

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: How do I re-read a line?
by belg4mit (Prior) on May 01, 2002 at 22:42 UTC
    This seems to work fine for me...
    my($index, $record) = (0); while (<$fh>) { chomp; s/\cM//; if (/^(\d)-RECORD$/) { $index = $1; $record->[$index]->{items} = []; } elsif (/ITEMNAME-(.*)/) { $record->[$index]->{name} = $1; } elsif (/ITEM \d-(.*)/) { push @{$record->[$index]->{items}}, $1; } }
    UPDATE: jeffa pointed out an undef in the record set. that's due to the lack of a 0-RECORD. Ignore it, or do $index = $1 -1, as you will.

    --
    perl -pew "s/\b;([mnst])/'$1/g"