3

I have this Perl code:

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

Now given s1, s2, s3 get references to $array[0], $array[1], $array[2] respectively. A switch case is possible. but how to get it in one or two statements.

10
  • 2
    Could you please clarify what you're going to achieve? Commented Jan 20, 2010 at 14:21
  • 1
    Why? You already have values 'a1', 'a2', 'a3' so why do you need the values of out the array? Maybe is $s1 $s2 and $s3 corresponded to array indexes instead of values... Consider perhaps using a hash... ? Commented Jan 20, 2010 at 14:22
  • 3
    @iamrohitbanga I think it is time for you take a break from posting and actually study Perl a little. I understand you are trying to get us to write what ever you need to write piece by piece and, of course, there is nothing wrong with that per SO's mission but your method will not help you learn anything. Commented Jan 20, 2010 at 15:14
  • 2
    @iarohitbanga: we understand that you're working on a college project and have other things to do. However, it's rude to expect us to do your work for you. We are also working and and have other things that we could do, but we are the sort who like to help. You are abusing our kindness though. Commented Jan 20, 2010 at 16:10
  • 1
    @iarohitbanga Isn't the purpose of doing a college project on Perl to learn Perl? Commented Jan 20, 2010 at 17:14

2 Answers 2

9

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 the index names and a different array for its values, well, it's 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';
Sign up to request clarification or add additional context in comments.

Comments

2

Your question is a little unclear, but I think you're asking how to find the index of an element in an array.

You can do that by using grep over a list of the array indexes:

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

You can achieve the same thing with a slightly nicer syntax using the List::MoreUtils module.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.