Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl (http://www.velocityreviews.com/forums/f17-perl.html)
-   -   Best practice to pass parameters to functions (http://www.velocityreviews.com/forums/t371939-best-practice-to-pass-parameters-to-functions.html)

* Tong * 09-28-2006 12:25 PM

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


Michal Nazarewicz 09-28-2006 02:12 PM

Re: Best practice to pass parameters to functions
 
* Tong * <sun_tong@users.sourceforge.net> 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--

Joe Smith 09-28-2006 07:37 PM

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


All times are GMT. The time now is 11:43 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.