Thursday, October 14, 2010

do, require, subroutine calls, pointers, references, dereferences

****************** docalled.pl *********************
use warnings;
$\ = "\n";
print "welcome : we are in doCalled.pl script";
$a = 10;
$b = 20;
$c = defined;
# $d = undef;

sub calc($a, $b)
{
$c = $a + $b;
print "C ::".$c;
}
&calc;

sub egsub
{
local($x, $y) = @_;
$result = $x+$y;
print "Result ::".$result;
# return($x++ * $y++);
}
&egsub(12,12);

# using arrays passed by reference (typeglobbing)
@a = ("1","2","3");
@b = ("4","5","6");
&egval(@a, @b);
sub egval
{
local(*a, *b) = @_;
# print @a; # prints 123
@a = ("a","b","c");
@b = ("d","e","f");
}
# print @a; print @b;
&egval; # array values will now change to a,b,c and d,e,f instead of 1,2,3 and 4,5,6
#print @a; print @b;

# array passed by reference
@a1 = ("apple","dog","cat");
@a2 = ("one","two","three");
&egsub7(\@a1, \@a2);
sub egsub7
{
local($a1ref, $a2ref) = @_;
#print $a1ref; # prints ARRAY(0x277c344)
#print $a2ref; # prints ARRAY(0x277c3a4)
#print @$a1ref; # prints appledogcat
#print @$a2ref; # prints onetwothree
@arr1 = @$a1ref;
print $arr1[0]; # prints apple
print "testing ".$$a1ref[1];
#foreach $e(@$a2ref)
$count = @$a2ref; # count stores length of the array
print $count;
for( $i=0; $i<=$count; $i++ ) { print $i; print $$a2ref[$i]; } @$a1ref = ("new","values","dude"); print @$a1ref; # prints newvaluesdude } # array of references @fruits = ("apple", "orange", "grape"); @vegies = ("onion", "carrot"); @collection = (\@fruits, \@vegies); $arry = $collection[0]; print "::".@$arry; # below - for loop statement prints both fruits and vegies items $len1 = @collection; #print $len1; # prints 2 for($i=0; $i<$len1; $i++) { $len1 = @{$collection[$i]}; # important step - to read array references # print $len1; # prints values as 3 and 2 as array size for($j=0; $j<$len1; $j++) { #print $collection[$i][$j]; or below statement , both same print $collection[$i]->[$j];
}
}

return 1;


*********************** docalling.pl **********************

# doCalling - call doCall script
# do - will load into memory, even if its already loaded, compile and executes.
# require - will not load if its already loaded, it take parameter as file path or filename.
# if both statements were used as below, its executing only once.
use warnings;
$\ = "\n";
do "E:\\practice perl programs\\doCalled.pl"; # do "doCalled.pl";
# require "E:\\practice perl programs\\doCalled.pl"; # require "doCalled.pl";
print "Yes doCalled.pl has executed !!!";
print "We are in doCalling.pl";
&calc;
&egsub(13,13);

No comments:

Post a Comment

 

©2010 Software Testing powered by Free Blogger Templates | Author : Anand Satish