Vijay
Vijay

Reputation: 67301

perl matched keywords and modify the keywords

I set an environment variable X first.

> setenv X "abc 12_3 abc"

Then I wrote a regex in perl trying to match the first column along with a space and the remaining string too in $2. here I print the first match $1

> echo $X|perl -lne '$_=~m/([^\s]*[\s])(.*)/;print $1'
abc 

here I print the second match $2.

> echo $X | perl -lne '$_=~m/([^\s]*[\s])(.*)/;print $2'
12_3 abc

Till now as it looks everything is OK. Now I thought of replacing all the underscore in the second match to spaces

> echo $X | perl -lne '$_=~m/([^\s]*[\s])(.*)/;$2=~s/_/ /g;'
Modification of a read-only value attempted at -e line 1, <> line 1.

well the error message says that $2 is read only.thats fine. so I copy $2 to some temporary variable $temp. so while copying its fine and $1 and $2 still exists as seen below:

> echo $X | perl -lne '$_=~m/([^\s]*[\s])(.*)/;$temp=$2;print $1.$2'
abc 12_3 abc

Now I tried replacing underscores with spaces in the temporary string $temp.

> echo $X | perl -lne '$_=~m/([^\s]*[\s])(.*)/;$temp=$2;$temp=~s/_/ /g;print $1.$2'

> 

My question is where are $1 and $2 gone? even though I made changes to $temp if its changing $2 what happened to atleast $1?

Upvotes: 2

Views: 146

Answers (2)

ikegami
ikegami

Reputation: 386396

s/_/ /g was successful, and it contains no captures, so it set all capture variables to undef.

This code will do what you want:

perl -nle'($x,$y)=/^(\S*\s+)(.*)/; $y =~ s/_/ /g; print $1.$2;'

Or even:

perl -ple's/^\S*\s+\K(.*)/ ($x=$1) =~ s{_}{ }g; $x /e;'

Or even (5.14+):

perl -ple's/^\S*\s+\K(.*)/ $1 =~ s{_}{ }gr /e;'

Upvotes: 1

pavel
pavel

Reputation: 3508

the statement $temp=~s/_/ /g resets the match variables; so if you want to use then after a new match/substitution, you'll have to store then in a variable...

Upvotes: 10

Related Questions