I am, as an exercise, trying to write a function that mimics pattern matching in langauges like Haskell and OCaml in Perl. The following code runs (I'm using Perl 5.18) and produces the following result.
$ perl pattern_matching.pl
Name "main::bob" used only once: possible typo at pattern_matching.pl
+line 50.
Use of uninitialized value $bob in print at pattern_matching.pl line 5
+0.
I think that's because the while loop
while (my ($k, $v) = each %$locals) {
local ${$k} = $v;
}
localizes each variable only within the body of the loop. I'm wondering what the right approach would be. Entire code below.
use strict;
use warnings;
sub same_keys {
my ($left, $right) = @_;
return unless ref $left eq 'HASH' and ref $right eq 'HASH';
return unless keys %$left == keys %$right;
for my $key (keys %$left) {
exists $right->{$key} or return;
}
return 1;
}
sub match ($$$) {
no strict 'refs';
my ($lhs, $rhs, $fun) = @_;
my $locals = {};
# populate locals
match_inner($lhs, $rhs, $locals);
while (my ($k, $v) = each %$locals) {
local ${$k} = $v;
}
return $fun->();
}
sub match_inner {
my ($lhs, $rhs, $locals) = @_;
if (ref $lhs eq '') {
$locals->{$lhs} = $rhs;
}
elsif (ref $lhs eq 'ARRAY') {
if (@$lhs == @$rhs) {
for my $i (0 .. $#$lhs) {
match_inner($lhs->[$i], $rhs->[$i], $locals);
}
}
}
elsif (ref $lhs eq 'HASH') {
if (same_keys($lhs,$rhs)) {
for my $k (keys %$lhs) {
match_inner($lhs->{$k}, $rhs->{$k}, $locals);
}
}
}
}
match "bob", 45, sub {
no strict;
print $bob;
};
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.