Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Perl CGI module use hyphens to start named arguments?

I am a novice. My question is what is the "-" before the keys (type, expires name etc) standing for? Why not just use the plain hash table way and discard the hyphen?

# #!/usr/local/bin/perl -w
use CGI; 
$q = CGI->new; 
print $q->header(-type=>'image/gif',-expires=>'+3d');
$q->param(-name=>'veggie',-value=>'tomato');
like image 813
lkahtz Avatar asked Dec 03 '22 03:12

lkahtz


2 Answers

The author already explained in the documentation.

Most CGI.pm routines accept several arguments, sometimes as many as 20 optional ones! To simplify this interface, all routines use a named argument calling style that looks like this:

print $q->header(-type=>'image/gif',-expires=>'+3d');

Each argument name is preceded by a dash. Neither case nor order matters in the argument list. -type, -Type, and -TYPE are all acceptable. In fact, only the first argument needs to begin with a dash. If a dash is present in the first argument, CGI.pm assumes dashes for the subsequent ones.

Several routines are commonly called with just one argument. In the case of these routines you can provide the single argument without an argument name. header() happens to be one of these routines. In this case, the single argument is the document type.

print $q->header('text/html');

like image 178
tszming Avatar answered Dec 18 '22 13:12

tszming


See perlop:

If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned. One effect of these rules is that -bareword is equivalent to the string "-bareword". (emphasis mine)

like image 26
Sinan Ünür Avatar answered Dec 18 '22 13:12

Sinan Ünür