Best practice to pass parameters to functions

T

* Tong *

Hi

Suppose there is a Perl equivalent function named 'ls' or 'sort', now what
is a good way to pass those switches to it? I.e., I need a systematical way
for Perl functions to handle dozens of switches like the 'ls' or 'sort'
command does.

please comment.

thanks
 
M

Michal Nazarewicz

* Tong * said:
Suppose there is a Perl equivalent function named 'ls' or 'sort', now what
is a good way to pass those switches to it? I.e., I need a systematical way
for Perl functions to handle dozens of switches like the 'ls' or 'sort'
command does.

#v+
sub foo () {
my %opts = @_;
if ($opts{'long'}) {
# use long output format
}
my $path = $opts{'path'} || '.';
# ...
}

# ...
foo( 'long' => 1, 'path' => '/usr', ... some more options );
#v-
 
J

Joe Smith

* Tong * said:
for Perl functions to handle dozens of switches like the 'ls' or 'sort'
command does.

It depends on whether you're talking about perl functions or
perl commands.

For a perl function, arrange it so that one of the arguments
to the function is a reference to a hash, and put all the options
and values in that hash.

For a perl command, which needs to parse options from the
command line, "use Getopt::Std;" is one module that will work.

Example:

use Getopt::Std;
#options: -s = number of seconds (or minutes) to between checks (default 3s)
my %opts; getopts('c:dnrs:t:z',\%opts);
my $debug = $opts{d} || 0;
my $sleep = $opts{s} || DefaultSleep; $sleep = m2s($sleep);
my $timecount = $opts{c} || DefaultCount;
$timecount = m2s($opts{t}) / $sleep if $opts{t};
my $showzero = $opts{z} || (@ARGV == 1 and -f $ARGV[0]);
my $check_r = $opts{r} || 0; # rsync/restore
test_num(-3..19) if $opts{n}; # -n for debugging num()


-Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top