You need to understand what the diamond operator does:
- Does the operator have an active filehandle, if not, shift an argument off @ARGV and open it for input as the active filehandle or if @ARGV is empty, set the active filehandle to STDIN.
- If called in list context, return all lines from the active filehandle.
- If called in scalar context and the filehandle is at the end of the file, return undef.
- Otherwise, return a single line from the filehandle.
That's pretty much it. I might be forgetting some subtleties.
The key bit, I've highlighted for you in bold. It uses @ARGV to figure out what file to read, and it alters that array!
So the first time you read a file using the diamond operator, you read it fine. The second time you try to read the file, the filename is no longer on @ARGV, so the diamond operator reads from STDIN instead.
| [reply] [d/l] [select] |
Hello again tobyink,
Thanks for the analytical explanation. I knew that the error was coming because it was reading the STDIN and it was expecting to be fed but I did not know how to overcome this problem.
Very nice trick to store the @ARGV temporarily on an array and then call it infinite times since it is not altered every time the loop runs. So simple and very clever at the same time.
Thank you for your time and effort.
Seeking for Perl wisdom...on the process of learning...not there...yet!
| [reply] [d/l] [select] |
> But share some light, why is it working with @ARGV = @preserved; # restore original @ARGV?
I' dunno well your skills but if you have not understood what the venerable monk tobyink says below, and directly answering to your cited above assertion:
the <> diamond operators consumes @ARGV so if you save a safe copy in @preserved you can refill @ARGV when you need ie first line of the two subs in the tobyink's example above.
As said below the <> diamond can also feed @ARGV opening SDTIN as last resource, so the above works because it restores @ARGV original contents at the top of the two testing subs.
L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
| [reply] [d/l] [select] |
| [reply] [d/l] [select] |