Perl: Using a conditional with an array

arrays, conditional-statements, loops, perl, syntax

Solution

String comparisons in Perl aren't done with `==` but with `eq`. Perl is does not consider the integer `13` different than the string `'13'` until you operate on them. String values that don't represent numbers in any obvious way (e.g. `'Harry'`) are coerced to a numeric value of zero. Thus, `$name=='Harry'` will always hold, but `$name eq 'Harry'` won't.

Take a look at `perldoc perlop` for more information.

Edited to add: If you had enabled the `warnings` pragma, then the interpreter would have pointed this out to you. In fact, it's always a good idea to `use strict` and `use warnings` in pretty much any Perl code that you write. In particular, this code (executed as a one-liner from the command line via `perl -e`):

use strict;
use warnings;
my @names=("Harry","Larry","Moe");

foreach my $name(@names)
{
  if($name=="Harry")
  {
    print "$name\n";
  }
}

produces the output

Argument "Harry" isn't numeric in numeric eq (==) at -e line 7.
Argument "Harry" isn't numeric in numeric eq (==) at -e line 7.
Harry
Argument "Larry" isn't numeric in numeric eq (==) at -e line 7.
Larry
Argument "Moe" isn't numeric in numeric eq (==) at -e line 7.
Moe

Problem

So I'll start of by saying I'm not very familiar with Perl. I have a project that I've been handed at work that requires quite a bit of Perl work. Most of it makes sense but I'm stuck on a very simple issue. I've simplified my code for example purposes. If I can get this to work I can code the rest of the project no problem, but for some reason I can't seem to get something as simple as the following to work for me: ``` #!/usr/local/bin/perl @names = ('Harry','Larry','Moe'); foreach $name (@names){ if($name == 'Harry'){ print $name; } } ``` Any help is greatly appreciated! Edit: fyi the output of the above is the following: ``` HarryLarryMoe ```

Original source