Sure, here you go:
use strict; use warnings;
use Algorithm::Diff qw/ LCS_length /;
( my $name = $ARGV[0] ) && length $ARGV[0] > 2 or die "Usage: `$0 <nam
+e>` (min. 3 letters)";
open my $fh, '<', '/usr/share/dict/words' or die $!;
my $found = 0;
while ( <$fh> ) {
next unless LCS_length( [ split //, $name ], [ split // ] ) == len
+gth $name;
$found++;
print "$found $_";
}
__END__
Things to maybe note:
- How to load a clever module and import its LCS_length function to do all the work :-)
- How to capture the user input from the command line in the array @ARGV
- How to open a file for reading
- How to create a counter and increment it in a loop
- How to read from an open filehandle line-by-line (which avoids reading it all into memory), using:
while ( <$fh> ) {
...
}
- The most obfuscated thing in this script: How to be lazy and not have to tell a function what to operate on by using the default argument, which is the current value of the magic variable $_. So in a loop I can say:
while ( <$fh> ) { # each line is loaded into $_ in turn
my @characters = split //;
}
, omitting the second argument to split, and Perl knows to Do The Right Thing. More self-documenting usage would be:
while ( my $line = <$fh> ) { # each line now in $line
my @characters = split //, $line;
}
Note that you can get documentation on many of Perl's built-in functions with
perldoc -f <function_name>, e.g.
perldoc -f split.
Hope this helps! have fun ....
edit: fixed missing parens
The way forward always starts with a minimal test.
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.