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:
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 characters { my ($self, $chars) = @_; $self->{buffered_text} .= $chars->{Data}; ... }
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; my $text = $self->{buffered_text}; $self->{buffered_text} = ''; return $text; }
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.sub get_buffered_text { my $self = shift; (($_, $self->{buffered_text}) = ($self->{buffered_text}, ''))[0]; }
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |