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

I have pulled a line out of a database thus.
$data_file="learn.data"; open(DAT, $data_file) || die("Could not open file!"); @raw_data=<DAT>; @results = grep( /^$line[0]/, @raw_data ); foreach( @results ) { $record = $_; }
Then I have split the line thus.
open(I, $data_path); $found=0; while(<I>){ chomp; @line = split(/\t/, $_); if($line[0] eq $GET{'id'}){ $found=1; last; } } close(I);
Puzzle is. How can I ask, What is the preceding line in the database.? Give me the line that was printed just before the one we just extracted.? May god bless your living sole . Nasa.

update (broquaint): title change (was What wize monk can help?)

Replies are listed 'Best First'.
Re: What wize monk can help?
by DamnDirtyApe (Curate) on Nov 27, 2002 at 22:00 UTC

    Tie::File will serve you well here.

    use Tie::File ; my $data_file="learn.data"; my $search_for = 'foo' ; tie my @raw_data, 'Tie::File', $data_file or die ; for ( my $row = 0 ; $row < $#raw_data; ++$row ) { if ( $raw_data[ $row ] =~ /$search_for/ ) { my $matching_row = $raw_data[ $row ] ; my $previous_row = $raw_data[ $row - 1 ] ; my $following_row = $raw_data[ $row + 1 ] ; ### And so on and so forth... } }

    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche
Re: What wize monk can help?
by John M. Dlugosz (Monsignor) on Nov 28, 2002 at 00:45 UTC
    At the end of the while loop's body, say $prev_line= $_; to save what you have before doing <I> again.

    I'd also go ahead and used a named variable instead of relying on $_ to still hold the line. Something like:

    my ($current_line, $prev_line); while($current_line=<I>){ chomp; @line = split(/\t/, $_); if($line[0] eq $GET{'id'}){ $found=1; last; } $prev_line= $current_line; } close(I); # value in $prev_line still good.