I am a beginner Perl student. I want to find different ways to do loops and modify an array from a function. So, here is what I have written so far. The last one ChangeArray6() doesn't work, and I don't know why. Also, what's the best way to deal with arrays? If my sub needs to change an array's contents, how should I write my code? What's the neatest, best, most memory-efficient way to do it from a sub?
use strict; use warnings; my @A = (0) x 20; PrintA(); ChangeArray1(); PrintA(); ChangeArray2(@A); PrintA(); ChangeArray3(@A); PrintA(); ChangeArray4(@A); PrintA(); ChangeArray5(\@A); PrintA(); ChangeArray6(@A); PrintA(); # # This function changes an array # sub ChangeArray1 { my $i = 0; LOOP: return if ($i >= @A); $A[$i++] = 1; # Write to global array goto LOOP; } sub ChangeArray2 { my $REF = \@_; # get reference for (my $i = 0; $i < @$REF; $i++) { $$REF[$i] = 2; } } sub ChangeArray3 { foreach my $X (@_) # $X = reference to each item { $X = 3; } } sub ChangeArray4 { my $i = @_; while ($i-- > 0) { $_[$i] = 4; # use direct reference } } sub ChangeArray5 { my $B = shift; # I don't understand this, but it works :P foreach my $X (@$B) { $X = 5; } } sub ChangeArray6 { @_ = (6) x @_; # This does not work. } sub PrintA { print "\n".join('', @A); }
In reply to Changing an array from a sub by harangzsolt33
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |