|Problems? Is your data what you think it is?|
How to safely use $_ in a library function?by perl-diddler (Hermit)
|on Sep 17, 2013 at 11:51 UTC||Need Help??|
perl-diddler has asked for the
wisdom of the Perl Monks concerning the following question:
I want to use $_ in a library function. I'm using it to pass a value to a "goto &sub" function that describe context of where the goto has come from.
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
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:
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".
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...