如何使用字符串访问Perl数组元素?

Roh*_*nga 3 perl

我有这个Perl代码:

@str = qw(a1 a2 a3);
my @array;
$s1 = 'a1';
$s2 = 'a2';
$s3 = 'a3';
Run Code Online (Sandbox Code Playgroud)

现在给出的s1,s2,s3得到引用$array[0],$array[1],$array[2]分别.开关盒是可能的.但如何在一两个陈述中得到它.

Leo*_*era 9

真正想要的是哈希,而不是数组.

my %hash = (a1 => 'val 1', a2 => 'val 2', a3 => 'val 3');
my $s1 = 'a2'; # you want to read this from a file?
$hash{$s1} = 'new val 2';
Run Code Online (Sandbox Code Playgroud)

现在,如果您仍然希望使用数组作为索引名称,并为其值使用不同的数组,那么,这取决于您,但您使用的是错误的工具.

use strict;
my @str = qw(a1 a2 a3);
my @array;

sub search_ref {
    my $s = shift;
    my $i = 0;
    foreach (@str) {
        if ($_ eq $s) {
            return \$array[$i];
        }
        $i++;
    }
    return undef;
}

my $ref = search_ref('a2');
$$ref = 'new val 2';
Run Code Online (Sandbox Code Playgroud)