in reply to Readbackwards usage

Hello jayu_rao,

The method File::ReadBackwards->new() takes a filename (i.e., a string) as its first (and only required) argument. But if you first say:

open my $read_log_file, '<', '/home/jay/my_perl_programs/log.txt' or d +ie $!;

you create $read_log_file as a file handle, which is something quite different. (It’s like a special kind of pointer that Perl uses to access a file.) You can see this if you try to print it as a string:

16:13 >perl -Mstrict -wE "open(my $fh, '<', '1184_SoPW.pl') or die; sa +y qq[>$fh<];" >GLOB(0x7ec4f8)< 16:14 >

If you then call File::ReadBackwards->new($fh) it will try to access a file named “GLOB(0x7ec4f8)” — and fail, because there is no file of that name.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: ReadBackwards usage
by jayu_rao (Sexton) on Mar 16, 2015 at 07:17 UTC
    Thanks much for the explanation Athanasius. This clears the doubt. Any suggestion on how I can use the file handle with ReadBackwards?

    The reason is that I would have to work with a temporary file and I would not know the name of the file that is created for giving the actual string.

    Regards,

    Jay

      Hello jayu_rao,

      Here are two possible solutions:

      (1) Create the temporary file using the core module File::Temp and get the filename together with the handle:

      use File::Temp 'tempfile'; ... my ($fh, $filename) = tempfile(); my $bw = File::ReadBackwards->new($filename) or die "Cannot read '$filename' backwards"; while (my $log_line = $bw->readline) { ... }

      (2) Use the File::ReadBackwards TIED HANDLE INTERFACE, which accepts a filehandle:

      my $filename = 'data.txt'; open(my $bw, '<', $filename) or die "Cannot open file '$filename' for reading"; tie *$bw, 'File::ReadBackwards', $filename or die "Cannot read '$filename' backwards"; while (my $log_line = <$bw>) { ... }

      (Note the asterisk in tie *$bw — this is required. Also note the two different ways of reading the next line from the file: readline vs. <$bw>. N.B.: they are not interchangeable!)

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,