Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: if(my) scope

by ikegami (Pope)
on Apr 16, 2009 at 13:49 UTC ( #757983=note: print w/ replies, xml ) Need Help??


in reply to if(my) scope

if is implemented in terms of and, and neither creates a scope at run-time (i.e. they don't call ENTER+LEAVE). That means they don't affect the life (refcount) of variables.

if only affects the visibility of the variable, a compile-time effect.

yuck!

Update: Just to be clear, I'm talking specifically about the condition expression, not the body of the if.


Comment on Re: if(my) scope
Select or Download Code
Re^2: if(my) scope
by cdarke (Prior) on Apr 16, 2009 at 15:44 UTC
    Although I am sure you are right, how come:
    use strict; use warnings; use Devel::Peek; my $true = 1; my $ref; if ($true) { my $fred = 42; $ref = \$fred; } print Dump($$ref);
    Gives:
    SV = IV(0x3b2e0) at 0x3b2e4 REFCNT = 1 FLAGS = (PADMY,IOK,pIOK) IV = 42
    A reference count of 1, not 2?
      You changed
      if (my $var) { ... }
      to
      if (...) { my $var; ... }
      use strict; use warnings; use Devel::Peek; my $ref; if ((my $fred = 42), 1) { $ref = \$fred; Dump($$ref); } Dump($$ref);
      SV = IV(0x816a5cc) at 0x814f684 REFCNT = 2 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 42 SV = IV(0x816a5cc) at 0x814f684 REFCNT = 2 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 42

      A scope is created for if's curlies, but only a compile-time scope is created for the condition expression.

      Btw, note the proper usage of Dump.

        Doh!
Re^2: if(my) scope
by oha (Friar) on Oct 12, 2009 at 08:53 UTC
    i just realized that:
    open my $fh, '<', $file or die;
    so i'm asking myself if the possibility to setup a scope variable inside the argument of a function call is extended to _if_ statements too?

      This is fine:

      if (open(my $fh, '<', $qfn)) { ...read from $fh... } # $fh is out of reach here

      Perl doesn't care where the my is to the point that it allows the following (even though the behaviour is officially undefined):

      my $fh if ...;
        that's another thing:
        if(my $x = expr) { ... } # my always executed my $x if expr; # my is conditional if(expr) { my $x } # as above
        what i was saying is that if i can my on a arg of a function, maybe i can do the same in the "argument" of a if

        Oha

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2015-07-03 02:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (47 votes), past polls