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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.