tags:

views:

65

answers:

1

Hi,

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 this:

name,3,cc

How can I make this work?

Thanks

+8  A: 
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.

cjm