Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: How to eval an array element in regex's substitution

by ikegami (Patriarch)
on Oct 27, 2010 at 03:36 UTC ( #867596=note: print w/replies, xml ) Need Help??

in reply to How to eval an array element in regex's substitution

First, \1, etc are regex patterns. You want $1, etc.

Secondly, you have some serious misconception about the replacement expression.
Without /e, it's a double-quoted string literal that evaluates to the replacement.
With /e, it's a Perl expression which evaluates to the replacement.

my $s = 'Hello [2][1]'; my @a = ('x','y','z'); $s =~ s/\[(\d{1,2})\]/$a[$1]/g; print $s;

Replies are listed 'Best First'.
Re^2: How to eval an array element in regex's substitution
by pysome (Scribe) on Oct 27, 2010 at 04:48 UTC
    Thank your very much.
    Another question, maybe i refer to capture the square brackets ,
    and then "eval" the array element. Such as:
    $s =~ s/(\[\d{1,2}\])/$a$1/g; #output Hello $a[2]$a[1] # eval '$s="$s";'; ## Here ?
    How to eval the $s's value?
      my $s = 'Hello [2][1]'; my @a = ('x','y','z'); my $array_name = 'a'; { no strict 'refs'; $s =~ s/\[(\d{1,2})\]/$array_name->[$1]/g; } print $s;


      my $s = 'Hello [2][1]'; my @a = ('x','y','z'); my $array_name = 'a'; my $array_ref = do { no strict 'refs'; \@$array_name }; $s =~ s/\[(\d{1,2})\]/$array_ref->[$1]/g; print $s;

      But why do you want to use variable variable names?


      my $s = 'Hello [2][1]'; my @a = ('x','y','z'); my $array_ref = \@a; $s =~ s/\[(\d{1,2})\]/$array_ref->[$1]/g; print $s;


      my $s = 'Hello [2][1]'; my @a = ('x','y','z'); $s =~ s/\[(\d{1,2})\]/$a[$1]/g; print $s;

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://867596]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (1)
As of 2023-06-08 05:39 GMT
Find Nodes?
    Voting Booth?
    How often do you go to conferences?

    Results (29 votes). Check out past polls.