1

I am trying to create variable which belongs to object (non static) not class. In my following code I tried some things.

#!/usr/bin/perl -w

use Animal;

sub main{

    $animal1 = new Animal();
    $animal2 = new Animal();

    for (my $i=0; $i < 10; $i++) {
        $animal1->next_move();
        $animal2->next_move();
    }
    print "\n";
}

main();

my animal class looks like this

#!/usr/bin/perl -w
# 
# 
# Animal.pl

package Animal;

sub new
{
    my $class = shift;
    my $self = {
        _MOVE => 0,
    };
    bless $self, $class;
    return $self;
}

sub next_move{
    $self->{_MOVE}++;
    print $self->{_MOVE}." ";
}

1;

my output is

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 

while my expected out was

1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10

3 Answers 3

5

Change next_move to:

sub next_move{
    my ($self)=@_;
    $self->{_MOVE}++;
    print $self->{_MOVE}." ";
}

You would have caught this by using "use strict;" in your code.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I just started learning Perl, didn't know about strict. Will use it from now on.
@Ruturaj: You must always use strict and use warnings at the top of every Perl program. The -w option on the command line (or the shebang line of the program file) is not best practice. You also need to declare all of your variables using my as close as possible to their first point of use. It is also preferable to use ++$self->{_MOVE} instead of $self->{_MOVE}++. The name of the C++ programming language got everybody into bad habits!
I am using strict and warnings now. Thank you.
5

You should use strict and warnings.

You forgot to initialize the $self variable from the argument list in your method.

So, Perl just created a package variable called $self pointing to an anonymous hashref, and autovivified an entry _MOVE in that.

Also, don't use indirect object notation:

The problem is that Perl needs to make a number of assumptions at compile time to disambiguate the first form, so it tends to be fragile and to produce hard-to-track-down bugs.

Comments

0

I'd recommend adding "use warnings; use strict;" to the code. Then do a perl -cw to see if there are any errors.

Then you need to declare your $animal1 and $animal2 using "my", i.e. "my $animal1 = new Animal();"

Also, add my in front of "$self->{_MOVE}++;" in Animal-class.

1 Comment

If you include use warnings, then the w in -cw is unnecessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.