Search code examples
perlcommand-line-interface

Perl CLI code cannot do a string line appended


I'm trying to use a perl -npe one-liner to surround each line with =.

$ for i in {1..4}; { echo $i ;} |perl -npe '...'
=1=
=2=
=3=
=4=

The following is my first attempt. Note that the line feeds are in the incorrect position.

$ for i in {1..4}; { echo $i ;} |perl -npe '$_= "=".$_."=" '
=1
==2
==3
==4
=

I tried using chop to remove them line feeds and then re-add them in the correct position, but it didn't work.

$ for i in {1..4} ;{ echo $i ;} |perl -npe '$_= "=".chop($_)."=\n" '
=
=
=
=
=
=
=
=

How can I solve this?


Solution

  • chop returned the removed character, not the remaining string. It modifies the variable in-place. So the following is the correct usage:

    perl -npe'chop( $_ ); $_ = "=$_=\n"'
    

    But we can improve this.

    • It's safer to use chomp instead of chop to remove trailing line feeds.
    • -n is implied by -p, and it's customary to leave it out when -p is used.
    • chomp and chop modify $_ by default, so we don't need to explicitly pass $_.
    perl -pe'chomp; $_ = "=$_=\n"'
    

    Finally, we can get the same exact behaviour out of -l.

    perl -ple'$_ = "=$_="'