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

Hi Monks, I'm trying to replace multiple fields with blank spaces using one-liner

It works when i do one at a time, but not when i try and combine them

perl -ne 'substr ( $_,2,8 ) = " " && substr ( $_,15,5 ) = " + " if /^AB/ ; print $_;' $1 > $1.tmp

The simple test file is AB2014052012345HELLOWORLD

For some reason I end up with the following result: AB 12345 WORLD

there should be 8 blank spaces after AB, but i'm only getting 5. I am, however, correctly getting 5 spaces before WORLD.

Any help is much appreciated

Replies are listed 'Best First'.
Re: Multiple substr in Perl one-liner
by Anonymous Monk on May 19, 2014 at 16:25 UTC

    It's a precedence issue, the && is binding stronger than you think. Use extra parens, or use and, which has lower precedence. See perlop for the precedence table. Here's an explanation-by-code:

    $ perl -MO=Deparse,-p -e 'substr ( $_,2,8 ) = " " && substr ( $ +_,15,5 ) = " " if /^AB/' (/^AB/ and substr($_, 2, 8) = (substr($_, 15, 5) = ' ')); $ perl -MO=Deparse,-p -e 'substr ( $_,2,8 ) = " " and substr ( +$_,15,5 ) = " " if /^AB/' (/^AB/ and ((substr($_, 2, 8) = ' ') and substr($_, 15, 5) = ' + ')); $ echo "AB2014052012345HELLOWORLD" | perl -pe 'substr ( $_,2,8 ) = " + " && substr ( $_,15,5 ) = " " if /^AB/' AB 12345 WORLD $ echo "AB2014052012345HELLOWORLD" | perl -pe 'substr ( $_,2,8 ) = " + " and substr ( $_,15,5 ) = " " if /^AB/' AB 12345 WORLD

      ahhh...makes sense now. Thank you!