{
    "mode": "perldoc",
    "parameter": "Sub::Exporter::Tutorial",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Sub%3A%3AExporter%3A%3ATutorial/json",
    "generated": "2026-06-11T10:58:23Z",
    "sections": {
        "NAME": {
            "content": "Sub::Exporter::Tutorial - a friendly guide to exporting with Sub::Exporter\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 0.988\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "What's an Exporter?\nWhen you \"use\" a module, first it is required, then its \"import\" method is called. The Perl\ndocumentation tells us that the following two lines are equivalent:\n\nuse Module LIST;\n\nBEGIN { require Module; Module->import(LIST); }\n\nThe method named \"import\" is the module's *exporter*, it exports functions and variables into\nits caller's namespace.\n",
            "subsections": [
                {
                    "name": "The Basics of Sub::Exporter",
                    "content": "Sub::Exporter builds a custom exporter which can then be installed into your module. It builds\nthis method based on configuration passed to its \"setupexporter\" method.\n\nA very basic use case might look like this:\n\npackage Addition;\nuse Sub::Exporter;\nSub::Exporter::setupexporter({ exports => [ qw(plus) ]});\n\nsub plus { my ($x, $y) = @; return $x + $y; }\n\nThis would mean that when someone used your Addition module, they could have its \"plus\" routine\nimported into their package:\n\nuse Addition qw(plus);\n\nmy $z = plus(2, 2); # this works, because now plus is in the main package\n\nThat syntax to set up the exporter, above, is a little verbose, so for the simple case of just\nnaming some exports, you can write this:\n\nuse Sub::Exporter -setup => { exports => [ qw(plus) ] };\n\n...which is the same as the original example -- except that now the exporter is built and\ninstalled at compile time. Well, that and you typed less.\n"
                },
                {
                    "name": "Using Export Groups",
                    "content": "You can specify whole groups of things that should be exportable together. These are called\ngroups. Exporter calls these tags. To specify groups, you just pass a \"groups\" key in your\nexporter configuration:\n\npackage Food;\nuse Sub::Exporter -setup => {\nexports => [ qw(apple banana beef fluff lox rabbit) ],\ngroups  => {\nfauna  => [ qw(beef lox rabbit) ],\nflora  => [ qw(apple banana) ],\n}\n};\n\nNow, to import all that delicious foreign meat, your consumer needs only to write:\n\nuse Food qw(:fauna);\nuse Food qw(-fauna);\n\nEither one of the above is acceptable. A colon is more traditional, but barewords with a leading\ncolon can't be enquoted by a fat arrow. We'll see why that matters later on.\n\nGroups can contain other groups. If you include a group name (with the leading dash or colon) in\na group definition, it will be expanded recursively when the exporter is called. The exporter\nwill not recurse into the same group twice while expanding groups.\n\nThere are two special groups: \"all\" and \"default\". The \"all\" group is defined for you and\ncontains all exportable subs. You can redefine it, if you want to export only a subset when all\nexports are requested. The \"default\" group is the set of routines to export when nothing\nspecific is requested. By default, there is no \"default\" group.\n"
                },
                {
                    "name": "Renaming Your Imports",
                    "content": "Sometimes you want to import something, but you don't like the name as which it's imported.\nSub::Exporter can rename your imports for you. If you wanted to import \"lox\" from the Food\npackage, but you don't like the name, you could write this:\n\nuse Food lox => { -as => 'salmon' };\n\nNow you'd get the \"lox\" routine, but it would be called salmon in your package. You can also\nrename entire groups by using the \"prefix\" option:\n\nuse Food -fauna => { -prefix => 'cutelittle' };\n\nNow you can call your \"cutelittlerabbit\" routine. (You can also call \"cutelittlebeef\", but\nthat hardly seems as enticing.)\n\nWhen you define groups, you can include renaming.\n\nuse Sub::Exporter -setup => {\nexports => [ qw(apple banana beef fluff lox rabbit) ],\ngroups  => {\nfauna  => [ qw(beef lox), rabbit => { -as => 'coney' } ],\n}\n};\n\nA prefix on a group like that does the right thing. This is when it's useful to use a dash\ninstead of a colon to indicate a group: you can put a fat arrow between the group and its\narguments, then.\n\nuse Food -fauna => { -prefix => 'lovely' };\n\neat( lovelyconey ); # this works\n\nPrefixes also apply recursively. That means that this code works:\n\nuse Sub::Exporter -setup => {\nexports => [ qw(apple banana beef fluff lox rabbit) ],\ngroups  => {\nfauna   => [ qw(beef lox), rabbit => { -as => 'coney' } ],\nallowed => [ -fauna => { -prefix => 'willing' }, 'banana' ],\n}\n};\n\n...\n\nuse Food -allowed => { -prefix => 'any' };\n\n$dinner = anywillingconey; # yum!\n\nGroups can also be passed a \"-suffix\" argument.\n\nFinally, if the \"-as\" argument to an exported routine is a reference to a scalar, a reference to\nthe routine will be placed in that scalar.\n"
                },
                {
                    "name": "Building Subroutines to Order",
                    "content": "Sometimes, you want to export things that you don't have on hand. You might want to offer\ncustomized routines built to the specification of your consumer; that's just good business! With\nSub::Exporter, this is easy.\n\nTo offer subroutines to order, you need to provide a generator when you set up your exporter. A\ngenerator is just a routine that returns a new routine. perlref is talking about these when it\ndiscusses closures and function templates. The canonical example of a generator builds a unique\nincrementor; here's how you'd do that with Sub::Exporter;\n\npackage Package::Counter;\nuse Sub::Exporter -setup => {\nexports => [ counter => sub { my $i = 0; sub { $i++ } } ],\ngroups  => { default => [ qw(counter) ] },\n};\n\nNow anyone can use your Package::Counter module and he'll receive a \"counter\" in his package. It\nwill count up by one, and will never interfere with anyone else's counter.\n\nThis isn't very useful, though, unless the consumer can explain what he wants. This is done, in\npart, by supplying arguments when importing. The following example shows how a generator can\ntake and use arguments:\n\npackage Package::Counter;\n\nsub buildcounter {\nmy ($class, $name, $arg) = @;\n$arg ||= {};\nmy $i = $arg->{start} || 0;\nreturn sub { $i++ };\n}\n\nuse Sub::Exporter -setup => {\nexports => [ counter => \\'buildcounter' ],\ngroups  => { default => [ qw(counter) ] },\n};\n\nNow, the consumer can (if he wants) specify a starting value for his counter:\n\nuse Package::Counter counter => { start => 10 };\n\nArguments to a group are passed along to the generators of routines in that group, but\nSub::Exporter arguments -- anything beginning with a dash -- are never passed in. When groups\nare nested, the arguments are merged as the groups are expanded.\n\nNotice, too, that in the example above, we gave a reference to a method *name* rather than a\nmethod *implementation*. By giving the name rather than the subroutine, we make it possible for\nsubclasses of our \"Package::Counter\" module to replace the \"buildcounter\" method.\n\nWhen a generator is called, it is passed four parameters:\n\n*   the invocant on which the exporter was called\n\n*   the name of the export being generated (not the name it's being installed as)\n\n*   the arguments supplied for the routine\n\n*   the collection of generic arguments\n\nThe fourth item is the last major feature that hasn't been covered.\n"
                },
                {
                    "name": "Argument Collectors",
                    "content": "Sometimes you will want to accept arguments once that can then be available to any subroutine\nthat you're going to export. To do this, you specify collectors, like this:\n\npackage Menu::Airline\nuse Sub::Exporter -setup => {\nexports =>  ... ,\ngroups  =>  ... ,\ncollectors => [ qw(allergies ethics) ],\n};\n\nCollectors look like normal exports in the import call, but they don't do anything but collect\ndata which can later be passed to generators. If the module was used like this:\n\nuse Menu::Airline allergies => [ qw(peanuts) ], ethics => [ qw(vegan) ];\n\n...the consumer would get a salad. Also, all the generators would be passed, as their fourth\nargument, something like this:\n\n{ allerges => [ qw(peanuts) ], ethics => [ qw(vegan) ] }\n\nGenerators may have arguments in their definition, as well. These must be code refs that perform\nvalidation of the collected values. They are passed the collection value and may return true or\nfalse. If they return false, the exporter will throw an exception.\n"
                },
                {
                    "name": "Generating Many Routines in One Scope",
                    "content": "Sometimes it's useful to have multiple routines generated in one scope. This way they can share\nlexical data which is otherwise unavailable. To do this, you can supply a generator for a group\nwhich returns a hashref of names and code references. This generator is passed all the usual\ndata, and the group may receive the usual \"-prefix\" or \"-suffix\" arguments.\n"
                }
            ]
        },
        "PERL VERSION SUPPORT": {
            "content": "This module has a long-term perl support period. That means it will not require a version of\nperl released fewer than five years ago.\n\nAlthough it may work on older versions of perl, no guarantee is made that the minimum required\nversion will not be increased. The version may be increased for any reason, and there is no\npromise that patches will be accepted to lower the minimum required perl.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "*   Sub::Exporter for complete documentation and references to other exporters\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Ricardo Signes <rjbs@semiotic.systems>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is copyright (c) 2007 by Ricardo Signes.\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
            "subsections": []
        }
    },
    "summary": "Sub::Exporter::Tutorial - a friendly guide to exporting with Sub::Exporter",
    "flags": [],
    "examples": [],
    "see_also": []
}