harangzsolt33 has asked for the wisdom of the Perl Monks concerning the following question:
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); }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Changing an array from a sub
by tybalt89 (Monsignor) on Feb 13, 2018 at 02:40 UTC | |
by harangzsolt33 (Chaplain) on Feb 13, 2018 at 02:46 UTC | |
Re: Changing an array from a sub
by NetWallah (Canon) on Feb 13, 2018 at 06:52 UTC | |
Re: Changing an array from a sub
by Eily (Monsignor) on Feb 13, 2018 at 17:59 UTC | |
Re: Changing an array from a sub
by Marshall (Canon) on Feb 13, 2018 at 07:55 UTC | |
Re: Changing an array from a sub
by corenth (Monk) on Feb 13, 2018 at 17:17 UTC | |
Re: Changing an array from a sub
by jwkrahn (Abbot) on Feb 13, 2018 at 06:57 UTC | |
by hippo (Bishop) on Feb 13, 2018 at 09:14 UTC | |
Re: Changing an array from a sub
by rizzo (Curate) on Feb 14, 2018 at 05:30 UTC | |
by harangzsolt33 (Chaplain) on Feb 14, 2018 at 06:28 UTC |
Back to
Seekers of Perl Wisdom