Variables in Perl

In Perl, variables are declared implicitly when they are first used. Unlike Go, Perl doesn’t require explicit type declarations.

#!/usr/bin/perl
use strict;
use warnings;

# Variables in Perl are declared with a sigil ($, @, or %)
# followed by the variable name.
my $a = "initial";
print "$a\n";

# You can declare multiple variables at once.
my ($b, $c) = (1, 2);
print "$b $c\n";

# Perl automatically infers the type of variables.
my $d = 1;  # This is a number
print "$d\n";

# Variables declared without initialization are undef.
my $e;
print defined $e ? $e : "undef", "\n";

# Perl doesn't have a specific shorthand for declaration and initialization.
# You always use 'my' for lexical variables.
my $f = "apple";
print "$f\n";

To run the program:

$ perl variables.pl
initial
1 2
1
undef
apple

In Perl:

  1. Variables are declared using the my keyword for lexical scope.
  2. Perl uses sigils to denote variable types: $ for scalars, @ for arrays, and % for hashes.
  3. Perl doesn’t require explicit type declarations; it infers types automatically.
  4. Uninitialized variables are undef in Perl, which is similar to Go’s zero values.
  5. Perl doesn’t have a shorthand syntax like Go’s :=. You always use my for declaring variables.

Perl’s dynamic typing and implicit declarations make it more flexible but less strict than Go in terms of variable handling.

查看推荐产品

Comments powered by Disqus