0
sub new
{
    my $class = shift; #off the first element
    my $self = { };
    bless $self, $class;
    return $self;
}

Could anyone explain that? What is the use of the following three lines of code?

my $self = { };
    bless $self, $class;
    return $self;
2
  • 5
    These are OO basics. Commented Feb 6, 2014 at 7:49
  • It returns blessed object (in this case blessed hash ref). Commented Feb 6, 2014 at 8:06

1 Answer 1

6
  1. my $self = { }; creates an anonymous hash reference and stores it in the lexical variable $self.

  2. bless $self, $class; tells Perl that $self is not just any reference but actually an object of the class stored in $class. See bless in perldoc. bless $x, $y returns $x, and a subroutine always returns the value of the last executed statement unless explicetly told otherwise with a return statement, so the next line is optional, but good for readability.

  3. return $self; hands the value in $self (our special object reference) back to the calling function. See return in perldoc.

Edit:

To clarify, if you don't bless your reference, you won't be able to call methods on it. With bless you tell Perl, "look, from now on, associate the reference in $self with the class in $class, so that I can use the methods in that class on the reference."

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

4 Comments

suppose if placed my $self = { surname => "Galilei", forename => "Galileo", address => "9.81 Pisa Apts.", occupation => "bombadier" }; instead of my $self = { };. What will do this change?
Creates a hash refererence with those keys and values. I suggest you read up on hashes and perhaps just all of perlintro, as well as the aforementioned perlreftut and perlobj. Maybe pick up a book about Perl or find some good tutorials on PerlMonks and learn.perl.org.
I got it my comment use . please let me know,the use of @#array ?
Did you mean $#array? perlintro. Really.

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.