Rakesh
Rakesh

Reputation: 5

Error with accessing Array name in perl

I am doing a project in perl to search each elements from an array with all the other element and print the element and the array name in which the match occours.

Since the code is very long I'm explaining my problem with short example.

@array1=(sdasd,asdasd,abc);

if(abc=~/$array1[2]/)
{
print"Found!";
}
else
{
print"not found!"
}  

When i try searching for the pattern with the above method I get the answer. As there are many arrays and each array contain many elements i gave array name as @array1 , @array2 ... so that i can search using loops .

so i tried this method

@array1=(sdasd,asdasd,abc);

$arrayno = 1;
if(abc=~$array$arrayno[2])
{
print"Found!";
}
else
{
print"not found!"
}

I'm getting the following error

(Missing operator before $no?)
syntax error at C:\Perl64\prac\pp.pl line 4, near "$arra$no"
Execution of C:\Perl64\prac\pp.pl aborted due to compilation errors.

Upvotes: 0

Views: 71

Answers (1)

Hunter McMillen
Hunter McMillen

Reputation: 61512

It would be much simpler to hold all of your arrays in the same structure, you can place as many arrayrefs as you like inside of an array and iterate over them in a nested foreach loop:

my @arrays = ( [1,  2,  3,  4],
               [5,  6,  7,  8],
               [9, 10, 11, 12],
             );

my $array_counter = 1; 
foreach my $aref ( @arrays ) {
   foreach my $elem ( @$aref ) { # place arrayref in list context
      # do comparison here
      if ( # MATCH ) { print "Found match in Array $array_counter\n"; }
   }
   $array_counter++; # increment counter 
}

Upvotes: 1

Related Questions