How Perl CLI code can get a line appended directly
so below is wrong as lines need its newline char get dropped
$ for i in {1..7}; { echo $i ;} |perl -npe '$_= "=".$_."=" '
=1
==2
==3
==4
==5
==6
==7
=
by needing to stick on-np option, then can't get it work right:
$ for i in {1..7} ;{ echo $i ;} |perl -npe '$_= "=".chop($_)."=\n" '
=
=
=
=
=
=
=
=
=
=
=
=
=
=
Please solve it out, thanks much.
CodePudding user response:
You didn't specify what output you are trying to achieve. I'm guessing you want
=1=
=2=
=3=
=4=
...
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 ofchop
to remove trailing line feeds. -n
is implied by-p
, and it's customary to leave it out when-p
is used.chomp
andchop
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'$_ = "=$_="'