Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Sure, \@letters doesn't change. But when you leave the loop, @letters has been set back to r a c e--it looks like it hasn't changed, but it's really just been looped back to where it started.

A few more print()'s would make this clear...

Update: Fixed a typo, plus here's a modified version that makes it clearer what's happening (to me, anyhow):

#!perl -l use strict; use warnings; my $some_word = 'race'; my @letters = split //, $some_word; my (@array1, @array2); for (1 .. @letters) { my @new = @letters; push (@array1, \@new); push (@array2, \@letters); my $myshift = shift @letters; push(@letters, $myshift); print "$_ : @letters : $array1[-1] : $array2[-1]" } print ''; print "array1 contains:"; foreach my $aref (@array1) { print "$aref => @$aref"; } print ''; print "array2 contains:"; foreach my $aref (@array2) { print "$aref => @$aref"; } __END__ 1 : a c e r : ARRAY(0x8067740) : ARRAY(0x805f380) 2 : c e r a : ARRAY(0x807c91c) : ARRAY(0x805f380) 3 : e r a c : ARRAY(0x807c8c8) : ARRAY(0x805f380) 4 : r a c e : ARRAY(0x807c820) : ARRAY(0x805f380) array1 contains: ARRAY(0x8067740) => r a c e ARRAY(0x807c91c) => a c e r ARRAY(0x807c8c8) => c e r a ARRAY(0x807c820) => e r a c array2 contains: ARRAY(0x805f380) => r a c e ARRAY(0x805f380) => r a c e ARRAY(0x805f380) => r a c e ARRAY(0x805f380) => r a c e

Update 2: kiat asks: (W)hy doesn't \@letters point to the changed @letters inside the loop? That's just it--it does!


In reply to Re^3: Puzzled by array by trammell
in thread Puzzled by array by kiat

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 having a coffee break in the Monastery: (5)
As of 2024-04-19 04:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found