Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Which way is recommended ?

by matrixmadhan (Beadle)
on Nov 21, 2008 at 18:12 UTC ( #725198=perlquestion: print w/replies, xml ) Need Help??
matrixmadhan has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

This question should be a breeze to you all.

To open a file, read the contents, print them and close the file - I used to use the following piece of code

open(FILE, "<", $filename) or die "Unable to open file:$filename <$!>" +; while(<FILE>) { print "$_" } close(FILE);

But I have seen somewhere ( from net, not sure where ) that the below version is better.

1) Using $lfh instead of FILE directly
2) Using a variable $line as $line = <$lfh>, instead of directly using $_

my $lfh; open($lfh, "<", $filename) or die "Unable to open file:$filename <$!>" +; while( my $line = <$lfh>) { print "$line" } close($lfh);

Could you please explain the difference in usage and the better form of using it?


Replies are listed 'Best First'.
Re: Which way is recommended ?
by ccn (Vicar) on Nov 21, 2008 at 18:24 UTC

    Using lexical scope variable instead of global FILE you minimize unintentional name collisions and make the code more clear. The code reader will not be thinking about is FILE used anywhere else.

    Using human readable name $line instead of $_ you make the code more readable.

      Thanks for the reply
      So, for one-off codes/small codes it doesn't make sense right? Any form could be used.

        I would suggest that using the lexical variable for the filehandle is a good idea even in small one-off scripts. A very wise person once told me

        There is nothing more permanent than temporary code.

        Quite often quick-and-dirty scripts grow and become critical. Also, using the lexical filehandles is a good habit to cultivate.

        On the other hand, I often prefer to use $_ rather than an explicit variable in small loops. For me that's more of a style issue than anything else.

        G. Wade

        Exactly. If you are feeling (over)confident you can just code this:

        open (FILE, $filename) or die $!; print while <FILE>;

        Or on the command line:

        perl -pe '$_' file.txt

        UPDATE: thanks for the correction, quester


        (the triplet paradiddle with high-hat)
Re: Which way is recommended ?
by betterworld (Curate) on Nov 21, 2008 at 18:59 UTC
    instead of directly using $_

    The term "directly" is not quite correct here, because it suggests that $_ is used in any case.

    $_ will not be set if you write while( my $line = <$lfh> ).

    In my opinion, using $_ is not really elegant. It's a global variable and it will be visible to called subroutines even if you localize it. Well, in perl 5.10 you can avoid this my using my $_. But unlike with named variables, you won't get any errors from strict if you forget to my the variable.

      Also, a good part of Perl's operators and functions will modify $_ in some way. Even if you don't use it, a function you call might, and it'll get changed. This leads to hard-to-debug code of the worst kind...

      Reserve use of $_ to shell one-liners and map/grep blocks. The rest of the time assign your own variable.


      I should not have used the term 'directly' which means in any case with respect to $_; but that's not how it works.

      Too impressive. :)

        There is an implicit check for definedness when you do while (<FOO>) { }. See the perlop section on I/O Operators.

        while (<FOO>) { # do stuff } # terminates if we get a line that evaluates to false. while (my $l = <FOO>) { # do stuff } # only terminates at end of file (or error reading file) while (defined(my $l = <FOO>)) { # do stuff } # Let's take advantage of $_ and be somewhat safe(r). { local $_; while (<FOO>) { # do stuff } }

        TGI says moo

Re: Which way is recommended ?
by GrandFather (Sage) on Nov 21, 2008 at 22:15 UTC

    I'd go for:

    open my $inFile, "<", $filename or die "Unable to open $filename: $!\n +"; print <$inFile>; close $inFile;

    Perl reduces RSI - it saves typing

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://725198]
Approved by toolic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2017-03-30 19:38 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (363 votes). Check out past polls.