Why did you use }{ between $count++ and die?

The -n switch to perl wraps the entire script in a loop, as follows:

LINE: while (<>) { ... # your program goes here }

So the provided code deparses to this:

LINE: while (defined($_ = <ARGV>)) { $first ||= $_; $last = $_; ++$count; } { die "ERROR found $count lines. Need >5" unless $count > 5; print "FIRST:$first\nLAST:$last\n"; }

Note how the "butterfly operator" (that's }{) is used to add some extra bit of code that'll be run after the loop that -n adds finishes.

When i tried to run this code, I got following error message: syntax error at -e line 1, near "||=" syntax error at -e line 1, near "unless >"

As my brother said above: "Change to single quotes for Linux", i.e.:

perl -ne '$first ||=$_; $last=$_; $count++}{die qq(ERROR found $count +lines. Need >5) unless $count>5; print qq(FIRST:$first\nLAST:$last\n) +' YOUR-FILE-NAME-here.txt

This is to keep your shell from messing with the script by interpreting special characters.


In reply to Re^3: getting error "Use of uninitialized value $lines in concatenation (.) or string at line 6 by AppleFritter
in thread getting error "Use of uninitialized value $lines in concatenation (.) or string at line 6 by chiru

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.