← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 2 of 7

Classes और bless

एक class बस एक package है, और bless एक ordinary reference को उस class के एक object में बदल देता है।

In this page:

  1. Classes और bless

Classes और bless

bless एक reference और एक class name लेता है और reference को उस package से belonging mark करता है। Convention से new नाम का एक subroutine constructor है: यह object का data hold करने वाला एक hash reference बनाता है, इसे bless करता है और return करता है। Class->new(...) call करना class name को पहले argument की तरह pass करता है।

Note: hard-code करने की बजाय, आपको मिला class name bless को pass करें, जैसे bless($self, $class), ताकि subclasses काम करें।

उदाहरण: Classes and bless

perl
use strict;
use warnings;

package Dog;

sub new {
    my ($class, %args) = @_;
    my $self = {
        name  => $args{name}  || "Unnamed",
        sound => $args{sound} || "Woof",
    };
    return bless $self, $class;
}

package main;

my $dog = Dog->new(name => "Rex");
print "object class: ", ref($dog), "\n";
print "name stored: $dog->{name}\n";
print "sound stored: $dog->{sound}\n";
my $stray = Dog->new;
print "default name: $stray->{name}\n";

# Output:
# object class: Dog
# name stored: Rex
# sound stored: Woof
# default name: Unnamed
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. new से blessed reference return करना भूल जाना
  2. bless में class name hard-code करना
  3. वापस return किए reference की बजाय data की एक copy bless करना
चैप्टर सारांश
  • एक class एक package है
  • bless एक reference को एक package से tie करता है
  • new conventional constructor है
  • Objects आमतौर पर blessed hash references होते हैं
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.