in reply to Pass By Reference Inner Workings - Magic scalar operator

scalar is working for you, not because of its primary effect of forcing scalar context, but because of one of its secondary effects; of making your expression look like an expression, rather than just a bareword.

For example, you could also have said "my %x = %{+shift}". And that too would have worked.

The point is that %{shift} looks like a hash named "shift". %{+shift} looks like a dereferencing of the return value of the function named shift. And %{scalar shift} is recognized also by the compiler to be a set of function calls instead of just a literal variable name.


Dave

Replies are listed 'Best First'.
Re^2: Pass By Reference Inner Workings - Magic scalar operator
by diotalevi (Canon) on May 01, 2005 at 07:53 UTC

    davido, I'm surprised and ashamed for you. You should have told him about shift() before or instead of +shift. The former looks normal and has identical functionality while the latter is just an abuse of unary +.

    ... = %{shift()}

      :) Surprise and shame huh?

      Is it abuse, or acceptible use? Either way, the Perl world will survive my sin. ;) It's not all that unusual of a sight anyway, though to your point it is not as explicit as shift().

      Thanks for the gentle reminder that we shouldn't get too fancy.


      Dave

Re^2: Pass By Reference Inner Workings - Magic scalar operator
by geekondemand (Scribe) on May 01, 2005 at 08:32 UTC
    Am I correct that by saying something like
    sub mysub { my %x = %{+shift}; }
    I'll actually be copying all of the hash entries into a local variable... So if the hash passed into the subroutine is very large, it could be a performance hit? The paradigm I usually use is to shift into a scalar and then use dereference operator to access elements. This may be why... unless you have really good reasons to do it, should one stay away from the paradigm in the code segment above???

      First thing's first; diotalevi is right, my %x = %{shift()}; is by far the preferred method. I pulled out the unary + as a prefix that served a similar purpose to your use of scalar in this situation. But it's ultimately a bad example, and shift() is the proper way to do things. Treat a function like a function, (ie, use parens) rather than using the unary plus +.

      Now to answer your question: Yes, my %x = %{shift()}; makes a copy of the contents of the hash to a lexical variable. This does cost performance and memory. But there are times when you need a copy, and other times where it's fine to just work with the reference to the original hash, held in $_[0].


      Dave