farhanali:
First, let me say that any time you post code on the site, please wrap it with [code] [/code] tags. This will preserve the indentation and make reading the code much easier for us!
Secondly, let me commend you on the use of variable declarations (using
my var_name)! So many people don't do that, and IMHO, it's important, because it keeps the variable name usage in check, meaning it helps the coder and someone reading the code know when new variables are being added, and IMHO is just cleaner code.
Next, I would highly suggest that you always use the pragmas
strict and
warnings, as they will help you to write cleaner code, forcing certain standards (you'll understand that more as you code more, consider them as english teachers, but for perl). They are used as:
Code:
#!/usr/bin/perl
use strict;
use warnings;
... rest of code
As you have learned about the $_ perl variable, there is another one that is nice to have around. It is the $! error variable. Many functions put error messages into this variable when they fail.
open is one of them. It's not necessary to have, but it could be more informative to the user of the script, if you included it in the
open/die statement:
Code:
open FH, "/usr/share/dict/words" or die "Cant open word list: $!\n";
Not totally necessary, but nice to know why the open failed.
Your overall usage of perl is quite good, considering that this is your first real script.
Something to consider about this approach, though, is that it is a little bit slow. It's not bad, but loading the dictionary into memory and then duplicating it is generally not a good idea.... just because of the memory usage.
Here's another approach for you to consider with the script:
Open the dictionary and loop through it one line at a time. Make a copy of the dictionary item (single word). Then, for each letter in the input word, remove 1 of it from the dictionary word. If there aren't any letters left in the dictionary word, then you know it's an anagram.
There may be a better way, but I was simply looking for an option that would increase the speed of the program, as well as reduce memory usage.
If you'd like to see my version of the code, please ask.
TLD