perl-diddler has asked for the wisdom of the Perl Monks concerning the following question:
I.e. -- several function names are used to invoke the same "basic" functionality of ~100 lines of code, with the only difference being the name of what it was called with.
The basic functionality needs to access things like the calling context to determine how to format the return value (i.e. inspects wantarray, for example, among other vals).
This generally works fine with the calling functions saving
$_ via:
$_ = [[$_, ... (and other vals, like (caller 0)[3] to pick up function name)];
However, I ran into a rare case where I cannot assign to "$_". I tried making sure no local was in effect by passing
the $_ using "our $_ = [...]", but that hit the same snag:
Modification of a read-only value attempted at ..."
The problem was[is] that about 6 levels up the call stack, something called something called something [...] that was called from a loop:
Apparently, that usage sets the global '$_' to be an alias of each literal in a way that is making it "very difficult" to save and restore context -- part of which is not only the value of "$_" -- which was handled, but also the state of $_ (it being aliased to an unwriteable location) during the "for".for (qw (literal1 literal2 literal3)) { ... }
I rarely bumped into this problem, and only recently chased it down. The thing is, is that I'm unsure about how to efficiently save off $_ (such that it remains in pure, "portable", perl).
I thought it a bit odd that the global $_ would be set to an unwriteable location that remained, even when other subs were called. Might that not cause a host of other problems where "$_" is an implied operand?
I tried pushing the value onto the arg list, "@_" and popping it off in the target of the "goto &sub", but that caused behavior problems in other code that was previously working, so I rejected that fairly quickly.
So how can one save "$_" for use in a "called sub" that needs to save context so as to not disturb the called-from context? Or how can I check for and save the alias state and unalias so "$_" becomes useful again?
I'm assuming I'm having another "braino" moment, and forgetting something obvious, since with the global "$_" being unusable, perl tends to not work so well...
Ideas? Clue sticks appreciated...
Thanks...
|
|---|