Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Bachelor of Arts?

by dws (Chancellor)
on Aug 26, 2002 at 06:07 UTC ( [id://192775]=note: print w/replies, xml ) Need Help??


in reply to Bachelor of Arts?

More is revealed if you try
my $a='A'; print "".$a, $a++; __END__ AA
Indirectly, this goes toward explaining the behavior you're seeing.

What's happening under the covers in

my $a='A'; print $a, $a++;
is
  • Push the variable $a by reference (not a \ reference, which would pass a reference to a reference).
  • Push an object that represents the evaluation of the expression $a++, which has the side-effect of incrementing $a.
  • Call print
print then gets a stack frame that consists of $a, which is now 'B' as a result of the postincrement, and 'A', which is the result of evaluating the expression $a++.

So how does print "".$a, $a++ help explain this? Why doesn't it also print "BA"? That's because what gets passed as a first argument is a reference to an object that represents the evaluation of "".$a. At the time the expression was evaluated, $a still held 'A'.

This behavior is hinted at in perlsub, which explains

The array @_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated

Replies are listed 'Best First'.
Re: Re: Bachelor of Arts?
by BrowserUk (Patriarch) on Aug 26, 2002 at 14:35 UTC

    Thankyou for this clear and full explanation. I had read about and make use of (possibly too much) the aliasing of scalars in subs.

    I was also aware of there being some quirks of the use of ++ in pre and post form, and of its magical properties with respect to strings.

    I don't think I would ever have put them all together and realised this legitimate but unintuative behaviour though.

    Maybe its just one of those things you have to fall over before it becomes apparent. For me anyway.


    What's this about a "crooked mitre"? I'm good at woodwork!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://192775]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 12:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found