1) Always include the following at the top of your code:

use strict; use warnings; use 5.010; #if you are using perl 5.10 or greater

2) Don't use bareword file handles, like here:

open SHAKESPEARE, "complete_works.txt" or die "The haunted grave of Shakespeare won't open: $!";

A bareword filehandle is like a global variable, and global variables are bad because any part of your code can change a global variable, which makes debugging very difficult.

3) The following is called a 'typeglob':

*someName
A typeglob represents every perl variable with the name someName. Remember that in perl, these are all different variables:
$x -- scalar @x -- array %x -- hash &x -- subroutine (as well as a filehandle named x)

You can have all those variables in your program at the same time and there is no conflict. A typeglob is a reference to all of them. Once again, a typeglob is too much like a global variable, so generally you shouldn't use them for filehandles. Typeglobs are an intermediate to advanced topic.

4) Despite wind's recommendation, I would suggest that you always use the 3-arg form of open. If you want to read from a file, and you use the 2 arg form of open like this:

my $file = 'out.txt' open my $sh, $file or die ...

that will work fine. But suppose you are opening all the files in a directory, and $file gets set to the filename ">out.txt", well now you have a problem because the 2 arg form of open is going to open that file for writing. Sometimes it's better to be explicit with what you want to do in your code than rely on perl's implicit workings behind the scenes.


In reply to Re: Perl fIle handles by 7stud
in thread Perl fIle handles by perl_noob_101

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.