C, Perl, and cut and paste

On all released 5.10.* versions of Perl to date, the smart match operator can segfault if passed recursive data structures (like arrays that contain a reference to themselves).

I fixed that. The fix was pretty trivial: basically, the C code in the implementation of smart match was creating two hashes, called seen_this and seen_other; however, a typo made it so only seen_this was actually created. Segfaults ensued if the code was trying to use seen_other.

Do you see the language problem here? The code to create seen_this was copied and pasted to the code to create seen_other, but not all occurrences of the variable were renamed. Because in C, it's difficult to factorize this code without much programming overhead. (In that case, pointers to pointers.)

But in Perl, we have foreach and aliasing to $_. That's a great tool to avoid cut and paste, and reducing cut and paste will always improve maintainability. And that's why I prefer writing stuff like

$_ = $_ ? "<$_>" : "-" for $x, $y;
$x = $x ? "<$x>" : "-";
$y = $y ? "<$y>" : "-";

Leave a comment

About Rafaël Garcia-Suarez

user-pic I can haz Perl.