An interesting discovery about local has emerged in the course of debugging Class::MakeMethods (thanks to an excellent bug report from Adam Spiers).

Take a moment to predict the output of the code below before you run it.

#!/usr/bin/perl -w use strict; print_args( 123, 456, 789 ); sub print_args { tamper_args( 'All your arguments are belong to us.' ); print "My arguments were: " . join(', ', @_) . "\n"; } sub tamper_args { local @_ = ( 'This is not a potato.' ); }

On my machine (perl v5.6.1 for darwin), the call to tamper_args somehow clobbers the argument list visible to print_args, producing the following startling result: "My arguments were: All your arguments are belong to us."

This appears to be a conflict between the restoration of local values at the end of a sub {...} scope and the restoration of @_ that always happens at the end of a sub. In particular, the problem goes away if the local is inside another { } block (presumably because the two scope-exits are handled separately). It also goes away if tamper_args is called without a parenthesized argument list (presumably because there's no implicit local-ization in that case.

Now, I'll grant that there's generally no need to local @_ like this, but I've also not been able to find anything that says you're not allowed to do so -- perhaps this consitutes an actual Perl bug?


In reply to Don't local(@_) by simonm

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.