in reply to How do I extract data?

For something like this, one approach is to use a simple state machine.

In my solution below, I read the entire file into a hash, keyed by the second word on the "calendar:" lines.
my %entries; # key=calendar name; value=array(ref) of dates. my $calendar; my @dates; sub finish_pending_entry { if ( defined $calendar ) { $entries{$calendar} = [ @dates ]; } # re-init the state data: $calendar = undef; @dates = (); } while (<>) { chomp; if ( /calendar: (.*)/ ) { finish_pending_entry(); # possibly none, if this is the fi +rst line. $calendar = $1; } else { push @dates, $_; } } finish_pending_entry(); # possibly none, if file was empty.
Now, if you want the dates for calendar "Calendar_2_test", say, you'd simply access     @{  $entries{'Calendar_2_test'} }

jdporter
...porque es dificil estar guapo y blanco.

Replies are listed 'Best First'.
Re: Re: How do I extract data?
by jdporter (Paladin) on Dec 26, 2002 at 23:37 UTC
    Of course, you might like a more object-oriented approach:
    { package CalendarEntry; sub new { my $pkg = shift; bless { dates => [], name => shift, }, $pkg } sub add_date { my $self = shift; push @{ $self->{'dates'} }, @_; } } # end CalendarEntry. my @entries; # array of CalendarEntry objects. my $entry; while (<>) { chomp; if ( /calendar: (.*)/ ) { defined $entry and push @entries, $entry; $entry = new CalendarEntry $1; } else { $entry->add_date( $_ ); } } defined $entry and push @entries, $entry;
    Now you have an array of CalendarEntry objects in @entries. You can convert that into a hash, with key = entry name and value = array(ref) of dates, like so:      my %entries = map { $_->{'name'} => $_->{'dates'} } @entries; Then you can look things up as before:     @some_dates = @{ $entries{'Calendar_2_test'} };

    jdporter
    ...porque es dificil estar guapo y blanco.