ssr1012 ssr1012 - 6 months ago 8
Perl Question

What is the difference between using "" and '' and () when declaring variables?

I've seen several different ways to declare variables in Perl:

my $scalarVar = ""; my $scalarVar = ''; my $scalarVar = (); my $scalarVar;
my @arrayVar = ""; my @arrayVar = ''; my @arrayVar = (); my @arrayVar;
my %hashVar = ""; my %hashVar = ''; my %hashVar = (); my %hashVar;


What is the difference between using
""
and
''
and
()
?

Answer

"" and '' evaluate to an empty string.

In scalar context, () evaluates to undef. Idiomatically, one would use undef instead of () when one knows it will be evaluated in scalar context.

In list context, () does nothing. It's used as a placeholder where an expression is expected. Conceptually, it's viewed as an empty list.


When assigning to a scalar, the value is copied into the scalar.

When assigning to an array, the contents of the array are replaced with the assigned scalars.

When assigning to a hash, the list to be assigned is expected to be a list of key-value pairs. The contents of the hash are replaced with the assigned key-value pairs.


Scalars are undefined when created, and arrays and hashes are created empty, so

my $scalarVar = "";     # Creates a scalar containing an empty string.
my $scalarVar = '';     # Creates a scalar containing an empty string.
my $scalarVar = undef;  # Creates an undefined scalar. Uselessly noisy code.
my $scalarVar = ();     # Creates an undefined scalar. Uselessly noisy and weird code. 
my $scalarVar;          # Creates an undefined scalar.

my @arrayVar  = "";     # Creates an array containing one scalar (an empty string).
my @arrayVar  = '';     # Creates an array containing one scalar (an empty string).
my @arrayVar  = undef;  # Creates an array containing one scalar (undefined).
my @arrayVar  = ();     # Creates an empty array. Uselessly noisy code.
my @arrayVar;           # Creates an empty array.

my %hashVar   = "";     # Warns. Makes no sense since a list of k-v pairs expected.
my %hashVar   = '';     # Warns. Makes no sense since a list of k-v pairs expected. 
my %hashVar   = undef;  # Warns twice. Makes no sense since a list of k-v pairs expected.
my %hashVar   = ();     # Creates an empty hash. Uselessly noisy code.
my %hashVar;            # Creates an empty hash.