in reply to Re: Changing Local Variable Out of Context
in thread Changing Local Variable Out of Context
bareblocks help minimize scope, I think about using them whenever I program. Many programmers scope at the "sub" level, but it helps to scope even deeper- within a sub. In general my rules for tite code include:
Here where I want to get an XML value from a file I might usea Var's lifetime should be never preceed, or outlast, its usefulness Declare at the last possible moment; go out of scope at the earliest
my $XMLval=''; { open X,'myfile'; my @X= grep /<myfavoritetag>/,<X>; last unless @X; $X[0] =~ s/<\/?[^>]+>//g; # shoot the tag and end tag.. $XMLVal=$X[0]; } # here we have $XMLval ready to go , all cleaned up, # and @X is out of scope , # so no worries about it anymore or any other gobbltygook # in the braces
I could have, and used to, just let @X "hang around" until the sub exited. After 30 years in Perl though, I'm much more conscious of scope and it's hazards.
It also makes intent clearer- when leaving the bareblock, there is no ambiguity about if @X might be needed, or used, subsequently. Some bloke looking at my code won't have to try to "figure that out" later.
But worst of all are global vars. To me, using those is like depending on a "side effect". As a min, declare them in main , but where needed, PASS THEM in as a ref or by value.
Just some musings about scope...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Changing Local Variable Out of Context
by NERDVANA (Priest) on Jun 16, 2023 at 17:23 UTC | |
|
Re^3: Changing Local Variable Out of Context
by karlgoethebier (Abbot) on Jun 13, 2023 at 21:12 UTC | |
by misterperl (Friar) on Jun 14, 2023 at 14:13 UTC | |
by karlgoethebier (Abbot) on Jun 14, 2023 at 15:39 UTC | |
|
Re^3: Changing Local Variable Out of Context
by cavac (Prior) on Jun 14, 2023 at 14:55 UTC |