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

Accessors बनाना

Accessor methods hash को directly poke करने की बजाय एक object के data तक controlled access देते हैं।

In this page:

  1. Accessors

Accessors

एक getter एक field return करता है और एक setter इसे बदलता है, और अक्सर एक method दोनों करता है इस आधार पर कि एक argument दिया गया या नहीं। Accessors इस्तेमाल करना internal structure hide करता है, इसलिए आप callers तोड़े बिना बाद में representation बदल सकते हैं। आप no strict refs के साथ symbol table में closures assign करके names की एक list से कई accessors generate कर सकते हैं।

Note: defined की बजाय @_ > 1 से arguments की संख्या test करें, ताकि callers एक field को undef set कर सकें।

उदाहरण: Accessors

perl
use strict;
use warnings;

package Person;

sub new {
    my ($class, %args) = @_;
    return bless { name => $args{name}, age => $args{age} }, $class;
}

sub name {
    my $self = shift;
    $self->{name} = shift if @_;
    return $self->{name};
}

for my $field (qw(age email)) {
    no strict 'refs';
    *{"Person::$field"} = sub {
        my $self = shift;
        $self->{$field} = shift if @_;
        return $self->{$field};
    };
}

package main;

my $p = Person->new(name => "Ada", age => 36);
print $p->name, " is ", $p->age, "\n";
$p->name("Ada Lovelace");
$p->age(37);
$p->email('[email protected]');
print $p->name, " is ", $p->age, ", email: ", $p->email, "\n";
$p->age(0);
print "age set to 0: ", $p->age, "\n";

# Output:
# Ada is 36
# Ada Lovelace is 37, email: [email protected]
# age set to 0: 0
{# 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. class के बाहर से $obj->{field} में पहुँचना
  2. truth के लिए एक setter argument test करना और 0 या एक empty string reject करना
  3. getter में value return करना भूल जाना
चैप्टर सारांश
  • Accessors fields get और set करते हैं
  • ये internal structure hide करते हैं
  • यह देखने के लिए @_ check करें कि एक value दी गई या नहीं
  • Closures accessors generate कर सकते हैं
🔒

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.