Open comes in a number of flavours. The two parameter open combines the open mode and file name in the second parameter. The three parameter open seperates the mode (second parameter) from the file name (third parameter). If you use the two parameter open and especially if you don't specify the mode because you want input, a user supplied file name that starts with '<', '>' or any of the other mode characters will set the file mode. That can include doing some pretty interesting stuff like forking a child process!

Now for that Perl magic:

my $input = do {local $/; <AA>;};

The do lets you put a block of statements where an expression is allowed. The result of the do block is the result of the last statement evaluated.

The special variable $/ stores the input line seperator. By default this is whatever line end sequence is native on your system. By declaring it local we save the old value it had and set the value to undef. With $/ set to undef the <AA> reads the whole file - there is no line end seperator to match. <AA> is the last statement evaluated in the do block so its result is assigned to $input.

Remember though that this reads the whole file in to memory. If the file is small (say up to a few megs) that is no big deal. If the file is gigabytes in size then it can be a real problem. It's a neat thing to know about and use, but you have to suit it to the application.

Update: s|%/|$/|g


DWIM is Perl's answer to Gödel

In reply to Re^5: What is the right way of concatenating strings by GrandFather
in thread What is the right way of concatenating strings by cool

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.