Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Not sure how to handle this scope (updated)

by haukex (Bishop)
on Aug 18, 2021 at 18:04 UTC ( #11135934=note: print w/replies, xml ) Need Help??


in reply to Not sure how to handle this scope

I wouldn't re-use the same variable name for a lexical that has already been defined. Also, don't put a postfix if on a my, as its behavior is undefined - see the note at the bottom of the section Statement Modifiers. Instead, you could do:

my $self = OO->new( $cat ); { my $inner_self = $ARGV[0] eq 'Fido' ? OO->new( $dog ) : $self; say $inner_self->species(); }

Note you shouldn't use Indirect Object Syntax either.

Update: Added some details to the above. Plus, why don't you just do this?

my $self = OO->new( $ARGV[0] eq 'Fido' ? $dog : $cat );

It's also a bit unusual to use $self as the variable name for a newly created object, since $self is usually used as the first argument to a method call, i.e. it's an existing object.

Replies are listed 'Best First'.
Re^2: Not sure how to handle this scope (updated)
by Anonymous Monk on Aug 18, 2021 at 18:13 UTC
    Strongly agree. "Re-using" a variable name, particularly one like $self, is a recipe for obtuse code that will be very difficult for your inevitable successor to understand and debug.
      Thanks guys, I left out a lot of details- but the { } are actually a forked loop and the self that contains the mysql handle goes away for each fork. That's why I'm trying to do this- BUT I want to run sometimes forked , and sometimes not, and for the not case- I want to use the object from outside the loop.. I realize this if pretty fugly but there is a lot of motivation to do it.

      But aisde from all that the real question is why does self go undef, and not use the scope outside the braces?

        Maybe give the inner variable a different name and assign it the value from the "main" handle in the non-fork case?

        my $main_dbh = DBI->connect(...); while( 1 ) { my $dbh; if( $forked ) { $dbh = DBI->connect(...); } else { $dbh = $main_dbh; }; $dbh->selectall_arrayref($sql); }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2022-01-21 17:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (59 votes). Check out past polls.

    Notices?