开发者

What is wrong with this Perl code?

$value = $list[1] ~ s/\D//g;

syntax error at try1.pl line 53, near "] ~"

Execution of try1.pl aborted due to compilation errors.

I am trying to extract t开发者_运维知识库he digits from the second element of @list, and store it into $value.


You mean =~, not ~. ~ is a unary bitwise negation operator.

A couple of ways to do this:

($value) = $list[1] =~ /(\d+)/;

Both sets of parens are important; only if there are capturing parentheses does the match operation return actual content instead of just an indication of success, and then only in list context (provided by the list-assign operator ()=).

Or the common idiom of copy and then modify:

($value = $list[1]) =~ s/\D//;


maybe you wanted the =~ operator?

P.S. note that $value will not get assigned the resulting string (the string itself is changed in place). $value will get assigned the number of substitutions that were made


You said in a comment that are trying to get rid of non-digits. It looks like you are trying to preserve the old value and get the modified value in a new variable. The Perl idiom for that is:

 ( my $new = $old ) =~ s/\D//g;


And wanted \digits not non-\Digits. And have a superfluous s/ubstitute operator where a match makes more sense.

if ($list[1] =~ /(\d+)/) {
    $value = $1;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜