Somehow, I never got it right in first attempt and hence keeping a note here.
use strict;
use Getopt::Std;
use vars qw ($opt_d $opt_p $opt_r $opt_m $opt_t $opt_a);
getopts('d:p:r:m:t:a:') ;
$Depot = $opt_d;
$Product = $opt_p;
$Release = $opt_r;
$Branch = $opt_m;
$BuildTimeStamp = $opt_t;
$Action = $opt_a;
print ("Depot == $Depot");
The most important code to note is "use vars qw" declaration for opt_? kind of variables.
Saturday, March 14, 2009
Returning multiple arrays from a perl function
I wrote a perl function where I was trying to return 2 arrays from a perl function with statement,
return (@array1, @array2);
Return values were being collected as
my (@a1, @a2) = array_function ();
Even though there were no errors, my script was not working as expected. Only when I digged deeper I realized that returned arrays were not getting collected properly in @a1 & @2. Perl, was returning both of those arrays in concatenated manner and all the contents were getting assigned to single array @a1.
The fix:
To fix this issue, I changed the function to return references to array instead of arrays themselves. References are scalars and hence can be returned from functions just like any other scalar variables. Now my code inside a function changed to
return (\@array1, \@array2);
and calling statement changed to
my ($ref_a1, $ref_a2)= array_function ();
The way these references are used to retrieve the contents of array is to use a formation,
@{ref_a1} and @{ref_a2}
This one was a good learning!
return (@array1, @array2);
Return values were being collected as
my (@a1, @a2) = array_function ();
Even though there were no errors, my script was not working as expected. Only when I digged deeper I realized that returned arrays were not getting collected properly in @a1 & @2. Perl, was returning both of those arrays in concatenated manner and all the contents were getting assigned to single array @a1.
The fix:
To fix this issue, I changed the function to return references to array instead of arrays themselves. References are scalars and hence can be returned from functions just like any other scalar variables. Now my code inside a function changed to
return (\@array1, \@array2);
and calling statement changed to
my ($ref_a1, $ref_a2)= array_function ();
The way these references are used to retrieve the contents of array is to use a formation,
@{ref_a1} and @{ref_a2}
This one was a good learning!
Subscribe to:
Posts (Atom)