Hi.
The easiest way is to use the Getopt::Std module
( it is part of the standard distribution ).
Here is a sample program.
#!/usr/bin/perl -w
use strict;
use Getopt::Std;
use vars qw( $opt_s $opt_r $opt_n );
if( ! getopts('srn' ) )
{
die "Usage: filename.pl -srn filename\n";
#Example: perl myfile.pl -r test.txt
}
my @file = <>;
if( $opt_s )
{
@file = sort { $a cmp $b } @file;
}
if( $opt_r )
{
@file = reverse @file;
}
if( $opt_n )
{
@file = sort { $a <=> $b } @file;
}
Each command-line switch is assigned to its
respective scalar variable ( $opt_s, etc. ) and
if it exists, its individual value is 1.
You can also use multiple switches:
$perl myfile.pl -rn test.txt
# Reverse the contents of test.txt and perform
# a numeric sort on it.
# Sample runs:
C:\perl>perl pg8.pl -r test.txt
third line.
second line.
first line.
C:\perl>
C:\perl>perl pg8.pl -n test.txt
2
33
33
44
48
55
889
990
C:\perl>
C:\perl>perl pg8.pl -c test.txt
Unknown option: c
Usage: filename.pl -srn filename
C:\perl>
In the last example, I hadn't declared an $opt_c
in the line 'use vars qw ( $opt_s ... );' or
an if() statement to handle it. This is why
I received the message.
Hope this helps,
-Katie.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|