![]() |
|
|
|||||||
![]() |
PERL - Best practice to pass parameters to functions |
|
|
Thread Tools | Search this Thread |
|
|
#1 |
|
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 -- Tong (remove underscore(s) to reply) http://xpt.sourceforge.net/ -- Posted via a free Usenet account from http://www.teranews.com * Tong * |
|
|
|
|
#2 |
|
Posts: n/a
|
* Tong * <> writes:
> 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- -- Best regards, _ _ .o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o ..o | Computer Science, Michal "mina86" Nazarewicz (o o) ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo-- |
|
|
|
#3 |
|
Posts: n/a
|
* Tong * wrote:
> 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 |
|