开发者

perl regular expression hash with /e

开发者 https://www.devze.com 2023-01-08 18:44 出处:网络
I am looking to substitute hash value with perl regular expression /e option. The following code is not working for me.

I am looking to substitute hash value with perl regular expression /e option. The following code is not working for me.

 #!/usr/bin/perl

%hash=( 1 => "aa", 2 => "bb", 3 => "cc" );

$_="name,3";
s/^(name,(\d+).*)/$2,$hash{$1}/e;
print "$_\n";

exit 0;

I am expecting output like t开发者_如何学编程his:

name,3,cc

How can I make this work?

Thanks


s/^(name,(\d+).*)/$1,$hash{$2}/;

First, the parens are numbered in the order of the left paren, not the right paren. So $1 is the complete line, and $2 is the number, not the other way around.

Second, you don't want to use /e here. That causes the replacement to be evaluated as Perl code instead of just a string, which means that the , is treated as the comma operator and not just text. In scalar context, the comma operator evaluates both operands and returns the second one, and that isn't what you want here. If you had said

use warnings;

Perl would have told you "Useless use of a variable in void context", because the first expression is being ignored.

You should always start your programs with:

use strict;
use warnings;

Those two lines will help catch a lot of the common mistakes you might make. Sometimes you'll need to turn them off for part of your code, but you should understand the rules before you can decide when it's ok to break them.

If you do that in this program, you'll need to add a my before %hash.

0

精彩评论

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