I have written a sample program for you, using a hash. Maybe you won't truly understand it right now, but you will as you get more experienced with Perl. I'd suggest you read some books, tutorials and the Perl manual.
Click here to see my sample program for you :
#!perl
#these will help you write correct Perl scripts:
use strict;
use warnings;
# here, we declare all command names, and what subprocedure they shoul
+d call
my %commands = (
hello => \&hello,
world => \&world,
hacker => \&japh,
);
# now this is the user interface, or the command line
while (1) {
print "\n>> ";
my $command = <STDIN>;
#remove the newline from the end of the command
chomp $command;
#let's check if %commands has the given gommand
if (exists $commands{lc($command)}) {
&{$commands{$command}};
} else {
print "I don't get you...\n";
}
}
# and the actual subprocedures;
sub hello {
#the obligate first output :)
print "Hello World!\n";
}
sub world {
print "World, Hello!\n";
}
sub japh {
print "I am just another Perl hacker\n";
}
Try entering the commands 'hello', 'world' and 'hacker'.
Note that this program won't support arguments. That would be too complicated to show in a simple sample program like this.
Anyway, welcome to Perl Monks, and good luck learning Perl! As you will discover, it's an amazing language.
Update: there was an error in the code. I fixed it. I also corrected a spelling error.
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.