Why does Perl complain about "Can't change constant element in scalar assignment"?
I have this Perl routine that is causing the problem:
sub new
{
my $class = shift;
my $ldap_obj = Net::LDAP->new( 'test.company.com' ) or die "$@";
my $self = {
_ldap = $ldap_obj,
_dn ='dc=users,dc=ldap,dc=company,dc=com',
_dn_login = 'dc=login,dc=ldap,dc=company,dc=com',
_description ='company',
};
# Print all the values just for clarification.
bless $self, $class;
return $self;
}
what is wrong in this code:
i got this error Unable to change constant in scalar assignment on line Core.pm 12, next to "$ ldap_obj,"
a source to share
Since you are not using bold commas (=>), your underscore names on the left side are not auto-copied and therefore, without the ( '$'
, '@'
or '%'
) characters , they can only be subroutine names. Since you didn't declare these subtitles, perl takes them for constants and tells you that you cannot assign constants (or auxiliary calls).
The correct fix is to change the assignments to double arrows
_ldap => $ldap_obj, #...
Also, Brad's post reminds me, even if they were auto-quoted, you couldn't assign lexicon to a literal string, even if perl interpreted it as an auto-complete string.
a source to share
A Hash is just a list of key, value pairs. There is a syntactic construct that helps differentiate keys from values. It is known as the "fat arrow" =>
. This construct forces the left argument to be a string and then converts to a simple comma.
Here's what you wanted to write:
perl -MO=Deparse -e'$s = { a => 1 }'
$ s = {'a', 1};
-e syntax OK
This is what you actually wrote:
perl -MO=Deparse -e'$s = { a = 1 }'
Can't modify constant item in scalar assignment at -e line 1, near "1}"
-e had compilation errors.
$ s = {'a' = 1};
This is why I would recommend that you always run your Perl program with warnings enabled.
perl -w -MO=Deparse -e'$s = { a = 1 }'
Unquoted string "a" may clash with future reserved word at -e line 1.
Can't modify constant item in scalar assignment at -e line 1, near "1}"
-e had compilation errors.
BEGIN {$ ^ W = 1; }
$ s = {'a' = 1};
perl -w -MO=Deparse -e'$s = { a => 1 }'
Name "main :: s" used only once: possible typo at -e line 1.
BEGIN {$ ^ W = 1; }
my $ s = {'a', 1};
-e syntax OK
This final example shows why you should too use strict
.
perl -w -Mstrict -MO=Deparse -e'$s = { a => 1 }'
Global symbol "$ s" requires explicit package name at -e line 1.
-e had compilation errors.
BEGIN {$ ^ W = 1; }
use strict 'refs';
$ {'s'} = {'a', 1};
I had to declare $s
before trying to use it:
perl -w -Mstrict -MO=Deparse -e'my $s = { a => 1 }'
BEGIN {$ ^ W = 1; }
use strict 'refs';
my $ s = {'a', 1};
-e syntax OK
This is why I always run my Perl programs with
use strict;
use warnings;
a source to share