开发者

How can I combine two conditions in Perl?

开发者 https://www.devze.com 2023-01-01 01:05 出处:网络
I have two Perl one liners: perl-pe \"s/\\b$a\\b/$b/g if m/param1 /\"test and perl-pe \"s/\\b$a\\b/$b/g unless /^#/\" test

I have two Perl one liners:

perl  -pe "s/\b$a\b/$b/g if m/param1 /"  test

and

perl  -pe "s/\b$a\b/$b/g unless /^#/" test

How can I combine theif m/somthing/ and the unless /something/, like:

[root@localhost tmp]# 开发者_运维知识库 perl  -pe "s/\b$a\b/$b/g if m/param1/ unless /^#/"  test
syntax error at -e line 1, near "m/param1/ unless"


Maybe

perl  -pe "s/\b$a\b/$b/g if m/param1/ && ! /^#/"  test

does it.


unless is the same as if not. Judging by the way you've written the statement, I'm guessing you mean the following:

 perl  -pe "s/\b$a\b/$b/g if m/param1/ and not /^#/"  test

(Although, you might have meant or instead of and?)


On an unrelated note, you may want to add the \Q and \E escape sequences around $a in your regex:

perl  -pe "s/\b\Q$a\E\b/$b/g if m/param1 /"  test

They escape any characters that are special to regexes. If you intend for $a to hold a regex you should probably move the word boundary assertions (\b) into it.

No matter what you choose to do, you will need to be careful with values in $a and $b. For instance:

a="/"
b="slash"
perl  -pe "s/\b\Q$a\E\b/$b/g if m/param1 /"  test

will cause a syntax error. One solution to this is to not use environment variables to replace code. Perl allows you access to the environment through the %ENV hash:

perl -pe 's/\b\Q$ENV{a}\E\b/$ENV{b}/g if m/param1 /' test

Notice the use of single ticks to avoid treating $ENV as a shell variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号