(Note: below I talk about XML but it's not really all that relevant)

One thing it's useful to do while writing SAX modules is to store up the characters we've seen and process them in a start/end element handler. We do this because a SAX processor doesn't guarantee to us that it'll return all the characters at a time - it will often split on buffer boundaries, or entities, or CDATA boundaries.

So in my SAX handler I do:

sub characters { my ($self, $chars) = @_; $self->{buffered_text} .= $chars->{Data}; ... }
Now at some point you'll want to retrieve this text, and reset the buffer to the empty string. The really simple way to do this, that everyone will probably do on their first attempt is as follows:
sub get_buffered_text { my $self = shift; my $text = $self->{buffered_text}; $self->{buffered_text} = ''; return $text; }
But it occured to me - perl can swap variables without using a temporary variable using ($x,$y) = ($y,$x), and I wondered if I could (ab)use that. It turns out you can:
sub get_buffered_text { my $self = shift; (($_, $self->{buffered_text}) = ($self->{buffered_text}, ''))[0]; }
I was going to post this under obfuscation, because it probably belongs there, and it's so horrible that I'm actually not going to use it in production, but I thought some people here might find it neat to save on using a temp variable for this sort of thing.

Update: The $_ used there was a golfing optimisation. It works fine with undef or just about anything in that position.


In reply to Swapping object variables by Matts

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.