Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

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.


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

Replies are listed 'Best First'.
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);
    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) { ... }
      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.

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)) { 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


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://757983]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2018-06-25 03:20 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.