On 7/21/10 Wed Jul 21, 2010 10:17 AM, "newbie01 perl"
<[email protected]> scribbled:
> Hi all especially Perl teachers if anyone is ... :-)
>
> I just want to know if someone can provide some explanation on how does the
> argument iterator sub-routine below work. The Perl script is called from a
> UNIX Korn script as below:
>
> mail_smtp.pl -r ${MAILFROM} -s "$subject_line TEST EMAIL"
> [email protected] < /tmp/test_email.txt
>
> The Perl script is working and SMTP mail is working. Am just trying to
> understand how the getval sub-routine is parsing the command line arguments.
> the getval subroutine is as below.
>
> =================================================================
>
> sub getval {
> my $refVal = '';
> foreach $var(@ARGV) {
> if ($refVal ne '') {
> $$refVal = $var;
> $refVal = '';
> }
> else {
> $_ = $var;
> if (/-r/ ) {
> $refVal=\$fromUser;
> }
> elsif (/-f/) {
> $refVal=\$dataFile;
> }
> elsif (/-s/) {
> $refVal=\$subject;
> }
> else {
> @toUser = split(/[\;,]/,$var);
> }
>
> }
> }
> }
>
> =================================================================
>
> The portion that am confused at is at the following lines:
>
> $$refVal = $var;
That line assigns (copies) the contents of the $var variable to the location
referenced by the $refVal pointer. This will be either $fromUser, $dataFile,
or $subject, depending upon the option entered (-r, -f, or -s,
respectively).
>
> and
>
> $_ = $var;
> if (/-r/ ) {
> $refVal=\$fromUser;
> }
The above lines copy the contents of $var to $_, tests if $_ contains the
string '-r', and, if it does, sets $refVal to 'refer' to $fromUser.
A better form would be to test $var directly:
if( $var =~ /-r/ ) {
$refVal = \$fromUser;
}
> Does $_ contains the following values on each iteration?
$var, and hence $_ (since it is a copy of $var), will contain the elements
of the @ARGV array, one per iteration of the foreach loop.
If you use the GetOptions module, you can replace the getval subroutine with
something like this (untested):
use Getopt::Long;
GetOptions(
'r=s' => \$fromUser,
'f=s' => \$dataFile,
's=s' => \$subject
);
push(@toUser, split/[;,]/) for @ARGV;
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/