← Back to Perl Course | Chapter 8: Modules | Lesson 6 of 7

अपना Module बनाना

एक module एक package है जो आप reuse कर सकते हैं, और Exporter इसे अपने users को चुने हुए functions देने देता है।

अपना Module लिखना

एक module आमतौर पर same नाम plus .pm वाली एक file में saved package है, लेकिन आप एक script में सीधे भी एक define कर सकते हैं। use Exporter import add करना package को @EXPORT_OK (request पर) या @EXPORT (default से) में listed names export करने देता है। एक module file एक true value जैसे 1; से खत्म होनी चाहिए ताकि इसे load करना succeed हो।

Note: @EXPORT की बजाय @EXPORT_OK prefer करें, ताकि users को जो names चाहिए उनके लिए पूछना पड़े और आपका module इनका namespace न भर दे।

उदाहरण: Writing your own module

perl
use strict;
use warnings;

BEGIN {
    package MyMath;
    use Exporter 'import';
    our @EXPORT_OK   = qw(square cube);
    our %EXPORT_TAGS = (all => \@EXPORT_OK);

    sub square { return $_[0] ** 2; }
    sub cube   { return $_[0] ** 3; }
    sub hidden { return "not exported"; }
    $INC{'MyMath.pm'} = 1;
}

use MyMath qw(square cube);

print "square(5) = ", square(5), "\n";
print "cube(3) = ", cube(3), "\n";
print "full name still works: ", MyMath::hidden(), "\n";
print "hidden imported? ", (main->can('hidden') ? "yes" : "no"), "\n";

# Output:
# square(5) = 25
# cube(3) = 27
# full name still works: not exported
# hidden imported? no
{# 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. एक module file के अंत में true value भूल जाना
  2. @EXPORT के साथ default से कई names export करना
  3. file का नाम package से अलग रखना
चैप्टर सारांश
  • एक module एक .pm file में एक package है
  • Exporter names export करता है
  • @EXPORT_OK request पर export करता है
  • File एक true value से खत्म होनी चाहिए
🔒

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.