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

Miller
  • 34,962
  • 4
  • 39
  • 60
SriSri
  • 95
  • 1
  • 13

2 Answers2

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]};
}
Community
  • 1
  • 1
RobEarl
  • 7,862
  • 6
  • 35
  • 50
  • 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 .. – SriSri May 29 '14 at 07:28
  • 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 – SriSri May 29 '14 at 08:06
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];
sateesh
  • 27,947
  • 7
  • 36
  • 45
  • Thankyou for helping me ...please read the requirement elaborated in comments in the above discussion with @RobEarl – SriSri May 29 '14 at 07:33