When you run a command line program, the simplest way to provide arguments is to simply have the values on the command line. For example, you might have a program named 'sum, which would add together all the numbers passed in: sum 1 2 3 4 would return '10'.
That's great for simple arguments. If you want to calculate something about a vehicle, you might want to pass in the number of wheels, the vehicle weight and horsepower. Suddenly the order becomes significant, you have to put them in the right order. So a good idea is to give the arguments names, especially if the convertible attributes only apply to cars, the wings attributes only to airplanes, and the saddlebags only to motorcycles. So you might have a miles-per-gallon program, mpg, which is invoked: mpg --weight 500 --wheels 2 --cc 1100.
Similarly, subroutines are normally passed arguments by position: area( 4, 5). The modern trend is either to pass in a single hash reference containing named arguments, or to have separate named arguments, as above. The hash ref equivalent would look like below; some programs that accept on accept the other as well.
$dbcontext = Bio::DB::SimpleDBContext->new( {
-database => 'biosql'
-user => 'xxxx',
-pass => 'xxxx',
-dbname => 'biosql',
-host => 'localhost'
+,
-port => 3306, #
+optional
-driver => 'mysql',
} );
The arror '=>' is called a 'fat comma', because it acts as a comma separator, only with better visibility, but also stringifies the preceeding bareword term.
I was goign to say there is no reason to have hyphens on the labels, but I did think of one. If the labels were optional, someone might invoke the costructor with labelled arguments, in whichever order they like, or they could use ordered arguments, in a single, specified order. So the presence of the hyphens clarifies their intent. You might process it like this ...
# in Bio::DB::SimpleDBContext
sub new {
my $class = shift;
my %args;
if ( '-' eq substr 0,1, $_[0] ) {
die( "Odd number of named arguments.\n" )
if @_ % 2;
while ( @_ ) {
my $tag = shift @_;
my $val = shift @_;
$args{qw/database, user, pass, dbname, host, port, driver/} =
+ $val;
}
}
else {
my $args{arg1, arg2} = @_;
}
As Occam said: Entia non sunt multiplicanda praeter necessitatem.
|