#!/usr/cs/bin/perl # # File: ref.pl --- demonstrates pass-by-reference to subroutines. # ############################## integers ############################ $a = 1; $b = 1; &Inc1 ($a); &Inc2 (\$b); print "a = $a, b = $b\n"; sub Inc1 { # doesn't work ($x) = @_; $x++; } sub Inc2 { # works (*x) = @_; $x++; } ############################## strings ############################# $name1 = "James"; $name2 = "French"; &Stretch1 ($name1); &Stretch2 (\$name2); print "name1 = $name1, name2 = $name2\n"; sub Stretch1 { # doesn't work ($str) = @_; $str =~ s/./$& /g; } sub Stretch2 { # works (*str) = @_; $str =~ s/./$& /g; } ######################### multiple arrays ########################## @array1 = (1, 2, 3); @array2 = (4, 5, 6); (*array3, *array4) = SwapArrays (\@array1, \@array2); print "array1 = (", @array1, "), array2 = (", @array2, ")\n"; print "array3 = (", @array3, "), array4 = (", @array4, ")\n"; sub SwapArrays { # works (*a1, *a2) = @_; return (\@a2, \@a1); } #################################################################### # # The results of running this program are: # # a = 1, b = 2 # name1 = James, name2 = F r e n c h # array1 = (123), array2 = (456) # array3 = (456), array4 = (123) # ####################################################################