Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Perl cheat sheet

by Anonymous Monk
on Aug 21, 2006 at 18:57 UTC ( [id://568645]=note: print w/replies, xml ) Need Help??


in reply to Perl cheat sheet

What is the explanation of NEVER use "$foo" Isn't this just basic variable interpolation? Is it really slow? What's the reason to never do this?

Replies are listed 'Best First'.
Re^2: Perl cheat sheet
by ikegami (Patriarch) on Aug 21, 2006 at 19:32 UTC

    "$foo" creates a stringified copy of $foo. $foo will get stringified when it needs to get stringified. There's no reason to do it prematurely. For example, it prevents people from using object with stringification overloaded.

      Globals are an important exception here. If you log($!), you may easily have a clobbered $! by the time you use it. log("$!") gets a snapshot of the variable at the time of the call.

        That's something most people will never need to know.

        The problem is that new programmers love to put *everything* in quotes. While it's a bad idea to pass global (lexical and package) variables as arguments, that is probably not a problem you'll ever run into. Just about every sub already creates a copy of the value before it can change.

        sub logger { my ($arg) = @_; # The copying happens here, so ... # no need to do it in the caller. }

        One could even argue it's the sub's responsibility to protect global variables it changes if it uses @_ at any other point.

        $! was an unfortunate choice of variable. :-) It's a dualvar so it has different values if treated as a string or as a numerical.

        open my $fh, '<', 'this does not exist'; printf "%s (%d)\n", $!, $!; __END__ No such file or directory (2)
        It's better to just create a copy and pass that, if the subroutine doesn't copy the argument.

        lodin

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-20 05:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found