Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-23 17:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found