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

Packages और Namespaces

एक package एक named container है जो इसके subroutines और variables को बाकी सबसे अलग रखता है।

Packages और Namespaces

package statement current namespace बदलता है, इसलिए package Animal में greet नाम का एक subroutine actually Animal::greet है। Package variables बाहर से इनके full name से पहुँचे जा सकते हैं, जैसे $Animal::count। Default package, जब आप कोई नहीं लिखते, main है, और __PACKAGE__ token current वाले का नाम देता है।

Note: एक package block, package Name { ... }, declaration का scope braces तक limit करता है (Perl 5.14 से available)।

उदाहरण: Packages and namespaces

perl
use strict;
use warnings;

package Greeter {
    our $count = 0;
    sub hello {
        $count++;
        return "Hello from " . __PACKAGE__;
    }
}

package main;

print Greeter::hello(), "\n";
print Greeter::hello(), "\n";
print "hello called $Greeter::count times\n";
print "current package: ", __PACKAGE__, "\n";

# Output:
# Hello from Greeter
# Hello from Greeter
# hello called 2 times
# current package: main
{# 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. यह भूल जाना कि दूसरे package में एक subroutine को इसका full name चाहिए
  2. यह सोचना कि package names और file names same होने चाहिए
  3. यह मान लेना कि our से declared package variables private हैं
चैप्टर सारांश
  • package NAME namespace बदलता है
  • Full names Package::name जैसे दिखते हैं
  • main default package है
  • __PACKAGE__ current package का नाम देता है
🔒

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.