http://qs321.pair.com?node_id=867607


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

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?

Replies are listed 'Best First'.
Re^3: How to eval an array element in regex's substitution
by ikegami (Patriarch) on Oct 27, 2010 at 06:48 UTC
    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;

    Better:

    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?

    Good:

    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;

    Simplified:

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