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

Re: if(my) scope

by ikegami (Patriarch)
on Apr 16, 2009 at 13:49 UTC ( [id://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.

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);
    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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://757983]
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: (2)
As of 2024-04-19 19:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found