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

Masters of Perl, I seek your wisdom yet again. I have a sniplet that successfully takes the last line of file and puts it an array, but now I need to be able to test the last line with the second to the last and so on. I've read up on using seek, File::Backwards, and other methods. I would like to use File::Backwards as it appears to do everything that I need, but I'm not sure how to implement it, and I'm having problems. Thanks in advance!
# $last_current_schedule is the last line of schedule.txt open (CURRENTSCHEDULE, "calendars/$calendar/schedule.txt"); my $last_current_schedule; local $_; $last_current_schedule = $_ while <CURRENTSCHEDULE>; @last_current_schedule = split(/\t/, $last_current_schedule); close CURRENTSCHEDULE; if($last_current_schedule[1] != $second_last_current_schedule[ +1]) { $last_current_schedule[0] = $new_default_id; } else { # test second, third to last until equal. $bw = File::ReadBackwards->new( 'logfile.txt' ) or die "can't read 'log_file' $!" ; while( defined( $log_line = $bw->readline ) ) { print LOGFILE $log_line ; } }

Replies are listed 'Best First'.
Re: End of File Woes
by Tanalis (Curate) on Oct 25, 2002 at 20:00 UTC
    Heys,

    Firstly - if you're reading the file backwards, does it not make sense to store the first line you get (which is the last line of the file), store it somewhere and then compare to that, rather than reading the file forwards first and then backwards?

    The way I perceive the module as working is not too dissimilar to what you have:

    use strict; use File::ReadBackwards; my $bw = File::ReadBackwards -> new ("log.txt") or die; while (defined (my $line = $bw -> readline)) { print $line; } $bw -> close;

    That seems to work fine for me on Perl 5.61 (Suse 8.0). Couple of things that spring to mine - if the @last_current_schedule array you have defined involves non-numeric values, != will never be true (and hence the file will never be read) - you should be using ne - that tests whether strings are not equal.

    Last thing I can think of is to check that all your variables are referenced correctly - that you're not overwriting any data you need and that it's not getting lost somewhere.
    Make sure you have use strict; at the top of the script. It'd probably help to turn warnings on too - either use warnings; or use perl -w at compile-time (older versions of Perl). That should give you some idea, hopefully, as to where the script is falling over (it'll also tells you if you've done something stupid with a variable).

    Hope that helps ..
    --Foxcub.