Go Back   Velocity Reviews > Newsgroups > PERL
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply

PERL - Best practice to pass parameters to functions

 
Thread Tools Search this Thread
Old 09-28-2006, 01:25 PM   #1
Default Best practice to pass parameters to functions



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 *
  Reply With Quote
Old 09-28-2006, 03:12 PM   #2
Michal Nazarewicz
 
Posts: n/a
Default Re: Best practice to pass parameters to functions

* 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--
  Reply With Quote
Old 09-28-2006, 08:37 PM   #3
Joe Smith
 
Posts: n/a
Default Re: Best practice to pass parameters to functions

* 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
  Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump