How can I use a string to access a Perl array element?

I have this Perl code:

@str = qw(a1 a2 a3);
my @array;
$s1 = 'a1';
$s2 = 'a2';
$s3 = 'a3';

Now, this s1, s2, s3receives a reference to $array[0], $array[1], $array[2]respectively. Possible gearbox. but how to get it in one or two statements.

+3
source share
2 answers

What you really want is a hash, not an array.

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';

Now, if you still want to use an array for index names and another array for your values, well, it is up to you, but you are using the wrong tool for the job .

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';
+9
source

, , , .

, grep :

my ( $idx ) = grep { $str[$_] eq 'a1' } ( 0 .. $#str );

, List:: MoreUtils.

use List::MoreUtils 'firstidx';
my $idx = firstidx { $_ eq 'a1' } @str;
+2

Source: https://habr.com/ru/post/1729233/


All Articles