0

I have lot of arrays saved as data for my automation , now i need have one method which will return an array with a given name .How can i do that. Kindly help .

#!/usr/bin/perl -w
use strict;

my @array1 = (1..4);

sub retArray {
    my $arr = shift;
    print $arr;
    ##Here i need to get the array with String which i got from args 
}

my @arrayReturned = retArray('array1');

use Data::Dumper;

print "\n";
print Dumper(\@array1);

Thanks in advance

2 Answers 2

2

Put the array in a hash:

my %arrays = ( 'array1' => [1..4] );

sub retArray {
    my $array_name = shift;
    return @{$arrays{$array_name}};
}

A list may be more appropriate, see: How can I use a variable as a variable name in Perl?

my @arrays;
push @arrays, \@array1;
push @arrays, \@array2;

sub retArray {
    my $array_num = shift;
    return @{$arrays[$array_num]};
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou ...i will have to add all arrays to this hash in this case if i understood it right. This will be a manual effort again. I will be adding arrays with an automated program and appending new arrays to the file . Is there any other way out please ...Meanwhile i am exploring if i can use this way ...Thankyou for your help ..very kind of you ..
A list may not be an option as each array might have a lot of elements, basically i am saving XPATHS in array and returning array of elements which represent a Screen . Maintainability will reduce in that case i think
1

Create a hash with the array name as a key and value an anon array ref containing the values you want.

Say something like:

my %map_array_ref;
$map_array_ref{'array1'} = [1,2,3];

1 Comment

Thankyou for helping me ...please read the requirement elaborated in comments in the above discussion with @RobEarl

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.