Lazer
Lazer

Reputation: 94830

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 the digits from the second element of @list, and store it into $value.

Upvotes: 0

Views: 192

Answers (4)

brian d foy
brian d foy

Reputation: 132802

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;

Upvotes: 1

ysth
ysth

Reputation: 98398

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//;

Upvotes: 7

msw
msw

Reputation: 43487

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;
}

Upvotes: 0

newacct
newacct

Reputation: 122439

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

Upvotes: 1

Related Questions