Thanks for the guidance. I'm trying to digest it all.
Don't assign to a global variable without localising it. You just clobbered your parent's data.
I guess you mean like this:
use strict; use warnings; use 5.010; sub do_stuff { foreach (1..5) { &dangerous($_); say "calculation in do_stuff(): ", $_ * 10; } } sub dangerous { $_ = shift; $_ *= 100; say "calculation in dangerous(): $_" } &do_stuff(); --output:-- calculation in dangerous(): 100 calculation in do_stuff(): 1000 calculation in dangerous(): 200 calculation in do_stuff(): 2000 calculation in dangerous(): 300 calculation in do_stuff(): 3000 calculation in dangerous(): 400 calculation in do_stuff(): 4000 calculation in dangerous(): 500 calculation in do_stuff(): 5000
By the way, I'm calling all user defined functions using the syntax &func() because the llama 5th ed. merely says that the & prevents name clashes with perl functions, therefore beginners should use the & until they become familiar with the names of perl functions. However, from the comments I gather there is more to it than that.
I don't understand what local() does differently than my(). I read the docs, and I don't understand the difference.sub do_stuff1 { local $_ = shift; chomp; say; }
or even safer:
sub do_stuff1 {
${ local *_ } = shift;
chomp;
say;
}
The latter handles the case where $_ is tied or otherwise magical.
What does that * notation do, and could you give some more details why that is safer than local $_? Maybe an example?
Thanks.
In reply to Re^2: style guidance
by 7stud
in thread style guidance
by 7stud
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |