in reply to getting error "Use of uninitialized value $lines in concatenation (.) or string at line 6

too many errors in your code - here is a one-line alternative that takes the file name on the command line:
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
Change to single quotes for Linux.

        What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?
              -Larry Wall, 1992

  • Comment on Re: getting error "Use of uninitialized value $lines in concatenation (.) or string at line 6
  • Download Code

Replies are listed 'Best First'.
Re^2: getting error "Use of uninitialized value $lines in concatenation (.) or string at line 6
by chiru (Initiate) on Jul 03, 2014 at 05:21 UTC

    Thanks for your reply. I'm still trying to figure out your code. Why did you use }{ between $count++ and die? 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 >"

      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.