How to pass and read function or subroutine arguments in a perl script
All the arguments passed to a perl subroutine are packed in an array “@_”. The following script shows you how to access function arguments in a subroutine.
[nick@techpulp ~]# cat funargs.pl
#!/usr/bin/perl
sub myfun
{
my $i = 0;
$nargs = $#_+1;
print "Number of arguments: $nargs\n";
foreach $arg (@_) {
$i++;
print "Arg $i: $arg\n";
}
}
myfun("One", "Two");
[nick@techpulp ~]#
Let us run the above script.
[nick@techpulp ~]# ./funargs.pl Number of arguments: 2 Arg 1: One Arg 2: Two [nick@techpulp ~]#
If the subroutine is expected to take fixed number of arguments, you can simplify the script as following.
[nick@techpulp ~]# cat funargs.pl
#!/usr/bin/perl
sub myfun
{
my ($arg1, $arg2) = @_;
print "Arg 1: $arg1\n";
print "Arg 2: $arg2\n";
}
myfun("One", "Two");
[nick@techpulp ~]#
The output of of above script is:
[nick@techpulp ~]# ./funargs.pl Arg 1: One Arg 2: Two [nick@techpulp ~]#


about 10 months ago
I guess the focus is not about assigning dfaluet value. The following lists possible modifiers:Modifiers can be applied to the ${name} form of parameter substitution:${name:-word}if name is set and not null, it is substituted, otherwise word is substituted.${name:+word}if name is set and not null, word is substituted, otherwise nothing is substituted.${name:=word}if name is set and not null, it is substituted, otherwise it is assigned word and the resulting value of name is substituted.${name:?word}if name is set and not null, it is substituted, otherwise word is printed on standard error (preceded by name:) and an error occurs (normally causing termination of a shell script, function or .-script). If word is omitted the string ?parameter null or not set? is used instead.In the above modifiers, the : can be omitted, in which case the conditions only depend on name being set (as opposed to set and not null).If word is needed, parameter, command, arithmetic and tilde substitution are performed on it; if word is not needed, it is not evaluated.