Functional programming in Perl.


Someone told me that thisPython program is impossible to do in Perl. The purpose of this code is to read regex patters from a file and uses them to produce plurals of English nouns.
The sample file is here.

The code in question is:

import re

def rules(language):
for line in file('rules.%s' % language):
pattern, search, replace = line.split()
yield lambda word: re.search(pattern, word) and re.sub(search, replace, word)

def plural(noun, language='en'):
for applyRule in rules(language):
result = applyRule(noun)
if result: return result


The equivalent Perl code is actually:
#!/usr/bin/perl -w

use strict;

sub fileByLine
{
my ($file, $sub) = @_;
my $fh;
open $fh, $file;
return sub
{
my $line = <$fh>;
chomp $line;
return $sub->($line);
}
}

sub rules
{
my ($file) = @_;
my $regex = sub
{
my ($line) = @_;
my ($pattern, $search, $replace) = split /\s+/, $line;
return sub {my $word = $_[0]; $word =~ /$pattern/ && $word =~ s/$search/$replace/ && $word};
};
return fileByLine("rules.txt", $regex);
}

sub plural
{
my ($noun) = @_;
my $iter = rules("rules.txt");
while (defined (my $applyRule =$iter->()))
{
my $result = &$applyRule($noun);
return $result if $result;
}
}

print plural($ARGV[0]);
print "\n";


There is no line() function in Perl that would read a file line by line and immediately process them, so I've written it and called it fileByLine().

Invoke this script like this:

-->perl plural.pl dog
dogs

-->perl plural.pl fax
faxes

-->perl plural.pl coach
coaches

-->perl plural.pl day
days

-->perl plural.pl vacancy
vacancies