kevin su kevin su - 5 months ago 7
Perl Question

How do I use an 'if' statement in Perl?

Consider:

#!/usr/bin/perl
if ($ARGV[0]=="-v") {
print "MY name: abc\n";
print "MY student ID:111110\n";
}
if ($ARGV[0]=="-s" && $ARGV[1]==printing_usage_file) {
open (INFILE, $ARGV[1]) or die "An input file is required as argument\n";
$totalbytes=0;
$data="";
while(<INFILE>) {
chomp();
@data=split(/,/);
$totalbytes += $data[1];
}
print "Total number of bytes printed: $totalbytes\n";
}


In this case, what I want is when I run
./perl.pl -v
, it prints
my name
and
id
.

When I run
./perl.pl -s printing_usage_file
, it prints the
totalbytes(printing_usage_file file is list like:aaa,240,ccc)
.

But here when I run
/perl.pl -v
or
./perl.pl -s printing_usage_file
it prints
my name
,
id
and the
totalbytes
. How can I fix it?

Answer

Your issue is that you are using the == operator to compare two strings when you need to use the eq operator.

$ perl -e 'print q{<}, "a" == "b", q{>}, "\n";'
<1>

If you use the eq operator, it will return an empty string which is a false value.

$ perl -e 'print q{<}, "a" eq "b", q{>}, "\n";'
<>
Comments