in reply to Grepping the filehandler

You probably don't run all the lines together in one script, but you include the first line and then just one of the second, third, or fourth one. It would have helped us to help you if you described in more detail what your code section meant.

The main problem is context. Both print on line 2 and list assignment on line 4 force list context, which means the whole contents of the file is returned from the readline. Line 3 uses readline in the binding operator which forces scalar context, which means it only reads one line from the file. If the very first line doesn't contain the error, it won't be printed.

Inserted: To shorten the code, you can use

print grep /error/, <$f>;
as grep also forces list context to its non-first argument(s).

Some other comments:

  1. Don't use my $a. $a is a special variable used in sort, lexicalising it can lead to sort not working.
  2. Check the return value of open and use the 3 argument variant:
    open my $f, '<', 'file' or die $!;

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Grepping the filehandler
by arunkumar.rk141 (Initiate) on Jul 23, 2020 at 16:36 UTC

    Thanks for your explanation.

    I tried to reference the file handler with a readline which gave the last line when it is dereferenced. Bit confused here as in the previously mentioned code it considers the first line of a file in a scalar context but when it comes to referencing last line is considered.

    open $f,'<','file' or die $!; my $r=\<$f>; print ref($f);#SCALAR print "$$r";# prints the last line of the code

      The \ operator in this case "puts its operand in list context, and creates a list of references to the scalars in the list provided by the operand", so the readline is in list context here and reading all the lines from the file. So in other words it's the same as my $r = \("Line1","Line2","...","LineN");, and a list in scalar context returns its last element.