简体   繁体   中英

Type conversion in Perl

I am trying to learn Perl here and the tutorial suggests the following code snippet after reading some file:

my $team_number = 42;
my $filename = 'input.txt';

open(my $fh, '<', $filename) or die "cannot open '$filename' $!";

my $found;
while(<$fh>) {
  chomp;
  last if($_ eq "Team $team_number");
}
die "cannot find 'Team $team_number'" if(eof $fh);

Why don't you need quotes around 42 when you are clearly comparing an integer to a string? Is Perl smart enough to do such type converting itself?

Perl is smart enough to do such type conversion itself.

  • An operator that requires a string coerces its operand into a string.
  • An operator that requires an integer coerces its operand into an integer.
  • An operator that requires a number coerces its operand into an integer or float.
  • etc

The literal 42 results in an integer value. But string concatenation [1] requires strings for operands, so it coerces it into a string.


  1. "Team $team_number" is identical to "Team " . $team_number "Team " . $team_number .

Although Perl is a strongly typed language , it does not have static types. The concept of distinct integers , strings or floats is not there in Perl.

Instead, when speaking about types , it refers to these three:

  • scalars
  • arrays
  • hashes

They are explained in the perldoc perldata .

Perl has three built-in data types: scalars, arrays of scalars, and associative arrays of scalars, known as "hashes". A scalar is a single string (of any size, limited only by the available memory), number, or a reference to something (which will be discussed in perlref). Normal arrays are ordered lists of scalars indexed by number, starting with 0. Hashes are unordered collections of scalar values indexed by their associated string key.

Both numbers and strings are scalars , which means that they are one single value.

There are, however, operators for numerical and string comparison, like == and eq . They are useful for example when sorting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM