To understand the difference, you must understand the distinction between an empty string and being undefined. An empty string, is a string defined to be empty. It is defined. Creating a scalar variable without assigning it anything or assigning it the special symbol undef are two ways of saying "I haven't chosen a value yet. Act accordingly." Thus:
- my $a; defined($a); returns false.
- my $a=undef; defined($a); returns false.
- my $a=''; defined($a); returns true.
- my $a=""; defined($a); returns true.
The difference between $a and $a=undef depends on whether or not $a has already been declared. my $a; and my $a=undef; two ways of writing the same thing. However, if you've already declared $a somewhere earlier in the script, $a; is an expression that evaluates to the value of $a. So my $a=1; $a; returns true. On the other hand, $a=undef; clears away whatever definition you gave to $a and makes it undefined again, so my $a=1; $a=undef; returns false.
There is no difference between $a=''; and $a="". Both assign $a an empty string. However, there is quite a difference if you put something between '...' and "...". For non-empty strings, single quotes are "non-interpolating" and double quotes are "interpolating". That means that between single quotes what-you-see-is-what-you-get: '$a' is just the two characters $ and a. But with double ("interpolating") quotes, Perl evaluates any variables found in between "..." so my $a=1; my $x="$a"; sets $x to "1" since that is the value of $a. For more information, see perlop.
Best, beth
|