This might be easier to understand with this similar function, which does the same for arrays:
sub palindrome { if (scalar(@_) >= 2) { my $first_dot = shift; my $slash_two = pop; return $first_dot eq $slash_two && palindrome(@_); } else {
The notation (?1) is a recursive reference to the beginning of the first bracket in the regular expression, \2 is the back reference in the current recursion to (.) . These two are tied to the beginning and end of "everything that matches the current recursion depth", so everything else is matched down to the next depth.
ikegami suspects this is faster:
sub palindrome { my $next = 0; my %symbols; my $s = join '', map chr( $symbols{$_} ||= $next++ ), @_; return $s =~ /^((.)(?1)\2|.?)\z/s; }
bazzargh
source share