develooper Front page | perl.perl5.porters | Postings from September 2013

Re: [perl #120047] perl should enable "$_" for use before calling subs

Thread Previous | Thread Next
Aaron Crane
September 30, 2013 12:45
Re: [perl #120047] perl should enable "$_" for use before calling subs
Message ID:
Linda Walsh via RT <> wrote:
> It didn't "blindly modify" it.  The value of $_ was *saved*
> in the code that made use of it and restored when done.

Not exactly; the code restored $_ when done, but only if it returned
without throwing an exception.  Your new code has the same problem
(ignoring its minor syntax errors):

> sub reader() {
>   my save=$_";
>   open(my $fh, "<myfile") or die "open:$!";
>   while (<$fh>) {
>   ...
>   }
>   $_=$save;
> }

If the file "myfile" does not exist (or the process doesn't have
permission to read it, or no more file descriptors are available, or a
host of other error conditions), this routine throws an exception (die
"open:$!").  That's almost always the correct thing to do when opening
a file fails, but it means that the rest of the routine doesn't run —
including the cleanup code.

If this code used either "local $_" or a lexical variable instead of
the manual save/restore, it would not have that problem — and nor
would it have problems when the existing value of $_ was read-only.

> That would *seem* to be a perfectly reasonable solution in most
> languages.  Even in assembler, if you use registers, you save them,
> you use them, you restore them.

That's a red herring; I'm not aware of a CPU with registers that can
alias a read-only value.

Aaron Crane **

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About