In Perl class today, a student turned in an assignment which vexes me. We are studying ARGV, but the result was not what I expected. His program (meme.pl) was:
#!/usr/bin/perl
$A = $ARGV[0];
chomp($A);
if ($A == "godzilla"){
print "$A\n";
}
else {
print "We need a monster's name\n";
}
If I type:
% ./meme.pl bob
the result is
% bob
So the variable assignment works, and but the condition ($A == "godzilla") is true no matter what is typed on the command line. I expected that since $ARGV[0] is "bob" and $A=$ARGV[0], then it should not true that $A="godzilla."
What am I missing? I have combed through this code for hours, and I know I am just overlooking some small thing.
Use eq, not ==, to test string equality:
if ($A eq "godzilla"){
More information is available at perldoc perlop.
Note: Adding use strict; and use warnings; to the top of your script would have led you in the right direction.
use strict; and use warnings; should be on...instant F in my book.
But no...evaluations of strings using "==" evaluate all strings - except those that start with a number like '123bob' (see comment below) - as numerical 0. That is why it is evaluating to true - it's "turning into" the statement 0 == 0. use warnings; would have told you something was up.
As many have said - use eq for strings.
More evidence and options can be found here: (http://perlmeme.org/howtos/syntax/comparing_values.html)
The pertinent excerpt (example program):
#!/usr/bin/perl
use strict;
use warnings;
my $string1 = 'three';
my $string2 = 'five';
if ($string1 == $string2) {
print "Equal\n";
} else {
print "Not equal\n";
}
From the above example, you would get warning messages and both strings would evaluate to zero:
Argument "five" isn't numeric in numeric eq (==) at ./test.pl line 8.
Argument "three" isn't numeric in numeric eq (==) at ./test.pl line 8.
Equal
You aren't getting those warnings...just the "Equal", thanks to the absence of use warnings; at the top of your - errr...your student's...cough... - code. ;)
When you are comparing strings, you must use "eq" instead of "==". So replace
($A == "godzilla")
by
($A eq "godzilla")
What the others said is correct about using eq to compare strings. However, the test passes, because when compared numerically with == the string 'bob' and the string 'godzilla' both evaluate to 0, so the test passes and you get bob.
Related
I defined some elements in an array:
my #arrTest;
$arrTest[0]=1;
$arrTest[2]=2;
#Result for #arrTest is: (1, undef, 2)
if($arrTest[1]==0)
{
print "one\n";
}
elsif($arrTest[1] == undef)
{
print "undef\n";
}
I think it should print "undef". But it prints "one" here...
Does it mean $arrTest[1]=undef=0?
How can I modify the "if condition" to distinguish the "undef" in array element?
The operator == in the code $arrTest[1] == 0 puts $arrTest[1] in numeric context and so its value gets converted to a number if needed, as best as the interpreter can do, and that is used in the comparison. And when a variable in a numeric test hasn't been defined a 0 is used so the test evaluates to true (the variable stays undef).
Most of the time when this need be done we get to hear about it (there are some exceptions) -- if we have use warnings; that is (best at the beginning of the program)† Please always have warnings on, and use strict. They directly help.
To test for defined-ness there is defined
if (not defined $arrTest[1]) { ... }
† A demo
perl -wE'say "zero" if $v == 0; say $v; ++$v; say $v'
The -w enables warnings. This command-line program prints
Use of uninitialized value $v in numeric eq (==) at -e line 1.
zero
Use of uninitialized value $v in say at -e line 1.
1
Note how ++ doesn't warn, one of the mentioned exceptions.
Why do I get a syntax error in the following script?
print "Enter Sequence:";
$a = <STDIN>;
if ($a=="A")|| ($a== "T")|| ( $a == "C")|| ($a== "G")
{
print $a;
}
else
{
print "Error";
}
First, you have a syntax error: The condition expression of an if statement must be in parens.
The second error is found by using use strict; use warnings;, something you should always do. The error is the use of numerical comparison (==) where string comparison (eq) is called for.
The final problem is that $a will almost surely contain a string ending with a newline, so a chomp is in order.
The immediate problem is that he entire logical expression for an if must be in parentheses.
In addition
You must use eq instead of == for comparing strings
Your input string will have a trailing newline, so it will look like "C\n" and will not match a simple one-character string. You need to chomp the input before you compare it
It is generally better to read from STDIN using <> rather than <STDIN>. That way you can specify an input file on the command line, or read from the STDIN if no input was provided
You must always put use strict and use warnings at the top of your program. That will catch many simple errors that you may otherwise overlook
You shouldn't use $a as a variable name. It is a symbol reserved by Perl itself, and says nothing about the purpose of the variable
It is best to use a regular expression for simple comparisons like this. It makes your code much easier to read and will usually make the execution very much faster
Please take a look at this program, which I think does what you want.
use strict;
use warnings;
print "Enter Sequence: ";
my $input = <>;
chomp $input;
if ( $input =~ /^[ATCG]$/i ) {
print $input, "\n";
}
else {
print "Error";
}
I'm just trying to check if a string is equal to "%2B", and if it does I change it to "+".
The problem lies in comparison.
if ($lastItem == "%2B"){
$lastItem = "+";
}
When $lastItem is something completely different (like "hello"), it will still go into the statement. I've been wracking my brain and I just can't tell where I've gone wrong. Does %2B have some special meaning? I'm very new to perl.
Thanks
You need to use eq when comparing strings, or perl will try to convert the string to a number (which will be 0), and you will find such oddities as "a" == 0 to evaluate true. And when comparing two strings, you will of course effectively get if (0 == 0), which is the problem you are describing.
if ($lastItem eq "%2B") {
It is important to note that if you had used use warnings, this problem would have been easier to spot, as this one-liner will demonstrate:
$ perl -wE 'say "yes" if ("foo" == "bar")'
Argument "bar" isn't numeric in numeric eq (==) at -e line 1.
Argument "foo" isn't numeric in numeric eq (==) at -e line 1.
yes
I think you really want the following:
use URI::Escape qw( uri_unescape );
my $unescaped_last_item = uri_unescape($escaped_last_item);
URI::Escape
Please use use strict; use warnings;!
Another example where turning on use warnings would have made it simpler to work out what was wrong.
$ perl -Mwarnings -e'$l = "x"; if ($l == "%2B") { print "match\n" }'
Argument "%2B" isn't numeric in numeric eq (==) at -e line 1.
Argument "x" isn't numeric in numeric eq (==) at -e line 1.
match
Below is my code, basically if the answer is "Y" then the script runs a message if it's something else then it closes.
#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
if($answer == "Y") {
print "COOOL\n";
} else {
system "exit"
}
Perl will tell you exactly what the problem is, if you ask it. Just add "use warnings" to your code.
#!/usr/bin/perl
use warnings;
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
if($answer == "Y") {
print "COOOL\n";
} else {
system "exit"
}
Then running it, gives:
$ ./y
Do you wish to run Program? [Y/N]:Y
Argument "Y" isn't numeric in numeric eq (==) at ./y line 6, <> line 1.
Argument "Y\n" isn't numeric in numeric eq (==) at ./y line 6, <> line 1.
COOOL
It's even better if you add "use diagnostics" as well.
$ ./y
Do you wish to run Program? [Y/N]:Y
Argument "Y" isn't numeric in numeric eq (==) at ./y line 7, <> line 1 (#1)
(W numeric) The indicated string was fed as an argument to an operator
that expected a numeric value instead. If you're fortunate the message
will identify which operator was so unfortunate.
Argument "Y\n" isn't numeric in numeric eq (==) at ./y line 7, <> line 1 (#1)
COOOL
Programming in Perl is far easier if you let Perl help you find your errors.
Remove newline. == is for numerical equality, for string you need eq.
chomp($answer);
if($answer eq "Y") {
When you wonder what's going on, start tracing your input. Ensure it is what you think it is:
#!/usr/bin/perl
use strict;
use warnings;
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
print "Answer is [$answer]\n";
Since you put the braces around the variable, you'll notice any extra whitespace. You should see extra stuff in $answer:
Answer is [Y
]
That's your clue that you need to do something to handle that.
And, strict and warnings help you find problems before they are problems.
Probably it will be better to use Term::Prompt or IO::Prompt. Don't reinvent the wheel :)
use IO::Prompt;
prompt -yn, 'Do you wish to run Program?' or exit;
You have newline character, chomp $answer
and $answer eq "Y"
You are using a numerical == to compare your strings.
You probably want to use "eq":
if($answer eq "Y") {
print "COOOL\n";
} else {
system "exit"
}
And as others have suggested you'll want to remove the newline at the end. Use chomp.
Besides the chomp/chop and eq vs ==, you also need to keep in mind the case of the answer. You are testing for UPPERCASE 'Y', I'm willing to bet you are entering lowercase 'y' and they are not equal. I would suggest using:
if (($answer eq 'y') || ($answer eq 'Y')) {
or use uc.
Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:
if (is_number($x))
{ ... }
would be ideal. A technique that won't throw warnings when the -w switch is being used is certainly preferred.
Use Scalar::Util::looks_like_number() which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this.
Note that the strings "inf" and "infinity" are treated as numbers.
Example:
#!/usr/bin/perl
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
my #exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);
foreach my $expr (#exprs) {
print "$expr is", looks_like_number($expr) ? '' : ' not', " a number\n";
}
Gives this output:
1 is a number
5.25 is a number
0.001 is a number
1.3e8 is a number
foo is not a number
bar is not a number
1dd is not a number
inf is a number
infinity is a number
See also:
perldoc Scalar::Util
perldoc perlapi for looks_like_number
The original question was how to tell if a variable was numeric, not if it "has a numeric value".
There are a few operators that have separate modes of operation for numeric and string operands, where "numeric" means anything that was originally a number or was ever used in a numeric context (e.g. in $x = "123"; 0+$x, before the addition, $x is a string, afterwards it is considered numeric).
One way to tell is this:
if ( length( do { no warnings "numeric"; $x & "" } ) ) {
print "$x is numeric\n";
}
If the bitwise feature is enabled, that makes & only a numeric operator and adds a separate string &. operator, you must disable it:
if ( length( do { no if $] >= 5.022, "feature", "bitwise"; no warnings "numeric"; $x & "" } ) ) {
print "$x is numeric\n";
}
(bitwise is available in perl 5.022 and above, and enabled by default if you use 5.028; or above.)
Check out the CPAN module Regexp::Common. I think it does exactly what you need and handles all the edge cases (e.g. real numbers, scientific notation, etc). e.g.
use Regexp::Common;
if ($var =~ /$RE{num}{real}/) { print q{a number}; }
Usually number validation is done with regular expressions. This code will determine if something is numeric as well as check for undefined variables as to not throw warnings:
sub is_integer {
defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
}
sub is_float {
defined $_[0] && $_[0] =~ /^[+-]?\d+(\.\d+)?$/;
}
Here's some reading material you should look at.
A simple (and maybe simplistic) answer to the question is the content of $x numeric is the following:
if ($x eq $x+0) { .... }
It does a textual comparison of the original $x with the $x converted to a numeric value.
Not perfect, but you can use a regex:
sub isnumber
{
shift =~ /^-?\d+\.?\d*$/;
}
A slightly more robust regex can be found in Regexp::Common.
It sounds like you want to know if Perl thinks a variable is numeric. Here's a function that traps that warning:
sub is_number{
my $n = shift;
my $ret = 1;
$SIG{"__WARN__"} = sub {$ret = 0};
eval { my $x = $n + 1 };
return $ret
}
Another option is to turn off the warning locally:
{
no warnings "numeric"; # Ignore "isn't numeric" warning
... # Use a variable that might not be numeric
}
Note that non-numeric variables will be silently converted to 0, which is probably what you wanted anyway.
rexep not perfect... this is:
use Try::Tiny;
sub is_numeric {
my ($x) = #_;
my $numeric = 1;
try {
use warnings FATAL => qw/numeric/;
0 + $x;
}
catch {
$numeric = 0;
};
return $numeric;
}
Try this:
If (($x !~ /\D/) && ($x ne "")) { ... }
I found this interesting though
if ( $value + 0 eq $value) {
# A number
push #args, $value;
} else {
# A string
push #args, "'$value'";
}
Personally I think that the way to go is to rely on Perl's internal context to make the solution bullet-proof. A good regexp could match all the valid numeric values and none of the non-numeric ones (or vice versa), but as there is a way of employing the same logic the interpreter is using it should be safer to rely on that directly.
As I tend to run my scripts with -w, I had to combine the idea of comparing the result of "value plus zero" to the original value with the no warnings based approach of #ysth:
do {
no warnings "numeric";
if ($x + 0 ne $x) { return "not numeric"; } else { return "numeric"; }
}
You can use Regular Expressions to determine if $foo is a number (or not).
Take a look here:
How do I determine whether a scalar is a number
There is a highly upvoted accepted answer around using a library function, but it includes the caveat that "inf" and "infinity" are accepted as numbers. I see some regex stuff for answers too, but they seem to have issues. I tried my hand at writing some regex that would work better (I'm sorry it's long)...
/^0$|^[+-]?[1-9][0-9]*$|^[+-]?[1-9][0-9]*(\.[0-9]+)?([eE]-?[1-9][0-9]*)?$|^[+-]?[0-9]?\.[0-9]+$|^[+-]?[1-9][0-9]*\.[0-9]+$/
That's really 5 patterns separated by "or"...
Zero: ^0$
It's a kind of special case. It's the only integer that can start with 0.
Integers: ^[+-]?[1-9][0-9]*$
That makes sure the first digit is 1 to 9 and allows 0 to 9 for any of the following digits.
Scientific Numbers: ^[+-]?[1-9][0-9]*(\.[0-9]+)?([eE]-?[1-9][0-9]*)?$
Uses the same idea that the base number can't start with zero since in proper scientific notation you start with the highest significant bit (meaning the first number won't be zero). However, my pattern allows for multiple digits left of the decimal point. That's incorrect, but I've already spent too much time on this... you could replace the [1-9][0-9]* with just [0-9] to force a single digit before the decimal point and allow for zeroes.
Short Float Numbers: ^[+-]?[0-9]?\.[0-9]+$
This is like a zero integer. It's special in that it can start with 0 if there is only one digit left of the decimal point. It does overlap the next pattern though...
Long Float Numbers: ^[+-]?[1-9][0-9]*\.[0-9]+$
This handles most float numbers and allows more than one digit left of the decimal point while still enforcing that the higher number of digits can't start with 0.
The simple function...
sub is_number {
my $testVal = shift;
return $testVal =~ /^0$|^[+-]?[1-9][0-9]*$|^[+-]?[1-9][0-9]*(\.[0-9]+)?([eE]-?[1-9][0-9]*)?$|^[+-]?[0-9]?\.[0-9]+$|^[+-]?[1-9][0-9]*\.[0-9]+$/;
}
if ( defined $x && $x !~ m/\D/ ) {}
or
$x = 0 if ! $x;
if ( $x !~ m/\D/) {}
This is a slight variation on Veekay's answer but let me explain my reasoning for the change.
Performing a regex on an undefined value will cause error spew and will cause the code to exit in many if not most environments. Testing if the value is defined or setting a default case like i did in the alternative example before running the expression will, at a minimum, save your error log.