dime has asked for the wisdom of the Perl Monks concerning the following question:

I am instantiating two objects in the following way:

my $query = new MyPackage::Query("utf8"); my $query2 = new MyPackage::Query("euc-jp");

Both end up working with euc. What is going wrong? Here's a short version of my constructor:

sub new { my $class = shift; $self->{input_enc} = shift; unless (defined $self->{input_enc}) { $self->{input_enc} = "euc-jp"; } #... bless($self, $class); return $self; }

Please tell me if I'm already messing up in the basics or if the mistake is likely to be in the #... part.

Replies are listed 'Best First'.
Re: Overwritten instance variables
by moritz (Cardinal) on Aug 03, 2009 at 09:06 UTC
    You are (implicitly) using a global variable $self, which is the same for all calls to new(). If you use a lexical inside the new method, all should be fine:
    use strict; use warnings; sub new { my $self = {}; my $class = shift; $self->{input_enc} = shift; unless (defined $self->{input_enc}) { $self->{input_enc} = "euc-jp"; } #... bless($self, $class); return $self; }

    By using strict you are forced to declare your variables with my or our, making it more obvious how they are scoped. And it catches typos in variable names for you at compile time.

Re: Overwritten instance variables
by tokpela (Chaplain) on Aug 03, 2009 at 09:14 UTC

    I tried to run your code and it didn't work.

    Try using strict and you will see that you are not instantiating $self correctly.

    Try something like this:

    use strict; use warnings; my $query = new MyPackage::Query("utf8"); my $query2 = new MyPackage::Query("euc-jp"); print "QUERY: [$query->{input_enc}]\n"; print "QUERY2: [$query2->{input_enc}]\n"; print "Done\n"; package MyPackage::Query; sub new { my $class = shift; my $self = {}; bless($self, $class); $self->{input_enc} = shift; unless (defined $self->{input_enc}) { $self->{input_enc} = "euc-jp"; } #... return $self; }

    This returns the correct result on my system:

    F:\>perl test_object_creation.pl QUERY: [utf8] QUERY2: [euc-jp] Done