spmlingam has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
cat /tmp/file | perl -e 'print "XXX\n" ;print <>; print "XXX"'
I am expecting, "XXX" will be added before and after each line in the /tmp/file.

but it is printing before first line and after last line.

is this correct?

pls suggest me, any other ways to do my requirement

Replies are listed 'Best First'.
Re: pipe output to perl
by ikegami (Patriarch) on Dec 04, 2008 at 12:11 UTC
    • The prints aren't in a loop, so why would it print before/after every line?

      perl -e 'while (<>) { print "XXX\n" ;print; print "XXX" }'

      Or use -n

      perl -ne 'print "XXX\n" ;print; print "XXX"'

      Or even -p

      perl -pe '$_ = "XXX\n" . $_ . "XXX"'
    • Then there's the useless use of cat. cat filename is a waste of resource. Use "<" instead.

      perl -e'...' < /tmp/file

      Or since <> (including -n and -p) treats the arguments as files to read, just

      perl -e'...' /tmp/file

    All together:

    perl -pe '$_ = "XXX\n" . $_ . "XXX"' /tmp/file
Re: pipe output to perl
by Corion (Patriarch) on Dec 04, 2008 at 11:55 UTC

    See perlrun, especially about the -p and -n switches. Your code does not contain any loop and hence Perl will only print XXX two times.

Re: pipe output to perl
by poolpi (Hermit) on Dec 04, 2008 at 15:36 UTC

    At the end...

    perl -pe 'END{print "XXX"} s/^/XXX\n/' file perl -ple 'END{print "XXX"} print "XXX"' file perl -lane 'END{print "XXX"} print "XXX\n$F[0]"' file

    hth,

    PooLpi

    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb