Structuring a Mojolicious Lite app - perl

I really like the fact that with Mojolicious::Lite I have an overview of routes in one file like this.
get '/foo/#bar' => sub {
my $c = shift;
...;
};
get '/baz/#foo' => sub {
my $c = shift;
...;
};
However in some cases the subs in the file grow too long and complex, and I'd like to split them off, while still keeping the Lite approach.
What's the best way to do that? Is it by creating controllers like in a full Mojolicious app, or should I create helpers in separate modules, and use them?
I can't find pointers to this in the docs.

Having hit something similar, and assuming you're wanting to keep Mojolicious::Lite - the easy solution is to 'outsource' subroutines into packages/modules, that you then use.
You don't need to do anything particularly special though - with Mojolicious::Lite you need 'helpers' which are basically a way of designating subroutines.
You can skip that, and create a separate module that just has subroutines defined that you import.
E.g.
#!/usr/bin/env perl
use strict;
use warnings;
package ExtraStuff;
sub generate_a_value {
return 4; # generated by random dice roll, so guaranteed to be fair and random
}
1;
Then just use that in your Mojolicious app.
Works quite nicely for 'config' type stuff too, especially if you're reusing it.
I wouldn't suggest doing it for direct HTML generation - Mojolicious already handles that for you, and probably better - but rather just 'outsourcing' stuff that you might be doing via helpers instead anyway.

When you unpack a lite app, you end up with your routes defined in YourApp.pm, in the startup sub... like in the guide. Since you can still dispatch to code-refs by passing the to via $r->get... and friends, you don't lose anything of that by moving away from light.
The full layout does encourage use of controllers, but you really don't have to do that.

Related

How do Perl modules "work"? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am confused about Perl modules. I get that a module can be used to dump a whole bunch of subs into, tidying main code.
But, what is the relationship between modules?
Can modules "use" other modules?
Must I use export, or can I get away with dropping that stuff?
How do I solve circular use? (Security.pm uses Html.pm and Html.pm uses Security.pm). I know the obvious answer, but in some cases I need to use Security.pm routines in Html.pm and vice versa - not sure how to get around the problem.
If I remove all "use" clauses from all of my modules ... Then I have to use full sub qualifiers. For example, Pm::Html::get_user_friends($dbh, $uid) will use Security to determine if a friend is a banned user or not (banned is part of Security).
I just don't get this module thing. All the "tutorials" only speak of one module, never multiple, nor do they use real world examples.
The only time I've come across multiple modules is when using OO code. But nothing that tells me definitively one way or another how multiple modules interact.
Modules in Perl come in several flavors and have several different things that make them a module.
Definition
Something qualifies as a module if the following things are true:
the filename ends in .pm,
there is a package declaration in the file,
the package name matches the filename and path; Data/Dumper.pm contains package Data::Dumper,
it ends with a 1 or another true value.
Conventions
Then there are some accepted conventions:
modules should usually only contain one package,
module names should be camel case and should not contain underscores _ (example: Data::Dumper, WWW::Mechanize::Firefox)
modules that are in small letters completely are not modules, they are pragmas.
Usually a module either contains a collection of functions (subs) or it is object oriented. Let's look at the collections first.
Modules as function collections
A typical module that bundles a bunch of functionality that is related uses a way to export those functions into your code's namespace. A typical example is List::Util. There are several ways to export things. The most common one is Exporter.
When you take a function from a module to put it into your code, that's called importing it. That is useful if you want to use the function a lot of times, as it keeps the name short. When you import it, you can call it directly by its name.
use List::Util 'max';
print max(1, 2, 3);
When you don't import it, you need to use the fully qualified name.
use List::Util (); # there's an empty list to say you don't want to import anything
print List::Util::max(1, 2, 3); # now it's explicit
This works because Perl installs a reference to the function behind List::Util::max into your namespace under the name max. If you don't do that, you need to use the full name. It's a bit like a shortcut on your desktop in Windows.
Your module does not have to provide exporting/importing. You can just use it as a collection of stuff and call them by their full names.
Modules as a collection of packages
While every .pm file called a module, people often also refer to a whole collection of things that are a distribution as a module. Something like DBI comes to mind, which contains a lot of .pm files, which are all modules, but still people talk about the DBI module only.
Object oriented modules
Not every module needs to contain stand-alone functions. A module (now we're more talking about the one directly above) can also contain a class. In that case it usually does not export any functions. In fact, we do not call the subs functions any more, but rather methods. The package name becomes the name of the class, you create instances of the class called objects, and you call methods on those objects, which ends up being the functions in your package.
Loading modules
There are two main ways of loading a module in Perl. You can do it at compile time and at run time. The perl1 compiler (yes, there is a compiler although it's interpreted language) loads files, compiles them, then switches to run time to run the compiled code. When it encounters a new file to load, it switches back to compile time, compiles the new code, and so on.
Compile time
To load a module at compile time, you use it.
use Data::Dumper;
use List::Util qw( min max );
use JSON ();
This is equivalent to the following.
BEGIN {
require Data::Dumper;
Data::Dumper->import;
require List::Util;
List::Util->import('min', 'max');
require JSON;
# no import here
}
The BEGIN block gets called during compile time. The example in the linked doc helps understand the concept of those switches back and forth.
The use statements usually go at the top of you program. You do pragmas first (use strict and use warnings should always be your very first things after the shebang), then use statements. They should be used so your program loads everything it needs during startup. That way at run time, it will be faster. For things that run for a long time, or where startup time doesn't matter, like a web application that runs on Plack this is what you want.
Run time
When you want to load something during run time, you use require. It does not import anything for you. It also switches to compile time for the new file momentarily, but then goes back to run time where it left of. That makes it possible to load modules conditionally, which can be useful especially in a CGI context, where the additional time it takes to parse a new file during the run outweighs the cost of loading everything for every invocation of the program although it might not be needed.
require Data::Dumper;
if ($foo) {
require List::Util;
return List::Util::max( 1, 2, 3, $foo );
}
It is also possible to pass a string or a variable to require, so you can not only conditionally load things, but also dynamically.
my $format = 'CSV'; # or JSON or XML or whatever
require "My::Parser::$format";
This is pretty advanced, but there are use-cases for it.
In addition, it's also possible to require normal Perl files with a .pl ending at run time. This is often done in legacy code (which I would call spaghetti). Don't do it in new code. Also don't do it in old code. It's bad practice.
Where to load what
In general you should always use or require every module that you depend on in any given module. Never rely on the fact that some other downstream part of your code loads things for you. Modules are meant to encapsulate functionality, so they should be able to at least stand on their own a little bit. If you want to reuse one of your modules later, and you forgot to include a dependency it will cause you grief.
It also makes it easier to read your code, as clearly stated dependencies and imports at the top help the maintenance guy (or future you) to understand what your code is about, what it does and how it does it.
Not loading the same thing twice
Perl takes care of that for you. When it parses the code at compile time, it keeps track of what it has loaded. Those things to into the super-global variable %INC, which is a hash of names that have been loaded, and where they came from.
$ perl -e 'use Data::Dumper; print Dumper \%INC'
$VAR1 = {
'Carp.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/site_perl/5.20.1/Carp.pm',
'warnings.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/5.20.1/warnings.pm',
'strict.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/5.20.1/strict.pm',
'constant.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/site_perl/5.20.1/constant.pm',
'XSLoader.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/site_perl/5.20.1/x86_64-linux/XSLoader.pm',
'overloading.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/5.20.1/overloading.pm',
'bytes.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/5.20.1/bytes.pm',
'warnings/register.pm' => '/home/julien/perl5/perlbrew/perls/perl-5.20.1/lib/5.20.1/warnings/register.pm',
'Exporter.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/site_perl/5.20.1/Exporter.pm',
'Data/Dumper.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/5.20.1/x86_64-linux/Data/Dumper.pm',
'overload.pm' => '/home/foo/perl5/perlbrew/perls/perl-5.20.1/lib/5.20.1/overload.pm'
};
Every call to use and require adds a new entry in that hash, unless it's already there. In that case, Perl does not load it again. It still imports names for you if you used the module though. This makes sure that there are no circular dependencies.
Another important thing to keep in mind with regards to legacy code is that if you require normal .pl files, you need to get the path right. Because the key in %INC will not be the module name, but instead the string you passed, doing the following will result in the same file being loaded twice.
perl -MData::Dumper -e 'require "scratch.pl"; require "./scratch.pl"; print Dumper \%INC'
$VAR1 = {
'./scratch.pl' => './scratch.pl',
'scratch.pl' => 'scratch.pl',
# ...
};
Where modules are loaded from
Just like %INC, there is also a super global variable #INC, which contains the paths that Perl looks for modules in. You can add stuff to it by using the lib pragma, or via the environment variable PERL5LIB among other things.
use lib `lib`;
use My::Module; # this is in lib/My/Module.pm
Namespaces
The packages you use in your modules define namespaces in Perl. By default when you create a Perl script without a package, you are in the package main.
#!/usr/bin/env perl
use strict;
use warnings;
sub foo { ... }
our $bar;
The sub foo will be available as foo inside the main .pl file, but also as main::foo from anywhere else. The shorthand is ::foo. The same goes for the package variable $bar. It's really $main::bar or just $::bar. Use this sparingly. You don't want stuff from your script to leak over in your modules. That's a very bad practice that will come back and bite you later.
In your modules, things are in the namespace of the package they are declared in. That way, you can access them from the outside (unless they are lexically scoped with my, which you should do for most things). That is mostly ok, but you should not be messing with internals of other code. Use the defined interface instead unless you want to break stuff.
When you import something into your namespace, all it is is a shortcut as described above. This can be useful, but you also do not want to pollute your namespaces. If you import a lot of things from one module to another module, those thing will become available in that module too.
package Foo;
use List::Util 'max';
sub foo { return max(1, 2, 3) }
package main; # this is how you switch back
use Foo;
print Foo::max(3, 4, 5); # this will work
Because you often do not want this to happen, you should chose carefully what you want to import into your namespace. On the other hand you might not care, which can be fine, too.
Making things private
Perl does not understand the concept of private or public. When you know how the namespaces work you can pretty much get to everything that is not lexical. There are even ways to get to lexicals to, but they involve some arcane black magic and I'll not go into them.
However, there is a convention on how to mark things as private. Whenever a function or variable starts with an underscore, it should be considered private. Modern tools like Data::Printer take that into account when displaying data.
package Foo;
# this is considered part of the public interface
sub foo {
_bar();
}
# this is considered private
sub _bar {
...
}
It's good practice to start doing things like that, and to keep away from the internals of modules on CPAN. Things that are named like that are not considered stable, they are not part of the API and they can change at any time.
Conclusion
This was a very broad overview of some of the concepts involved here. Most of it will quickly become second nature to you once you've used it a few times. I remember that it took me about a year during my training as a developer to wrap my head around that, especially exporting.
When you start a new module, the perldoc page perlnewmod is very helpful. You should read that and make sure you understand what it says.
1: notice the small p in perl? I'm talking about the program here, not the name of the language, which is Perl.
(Your question would be a lot easier to read if you used capital letters.)
can modules "use" other modules?
Yes. You can load a module within another module. If you had looked at almost any CPAN module code, you would have seen examples of this.
must i use export, or can i get away with dropping that stuff?
You can stop using Exporter.pm if you want. But if you want to export symbol names from your modules then you either use Exporter.pm or you implement your own export mechanism. Most people choose to go with Export.pm as it's easier. Or you could look at alternatives like Exporter::Lite and Exporter::Simple.
how do i solve circular use (security.pm uses html.pm and html.pm uses security.pm)
By repartitioning your libraries to get rid of these circular dependencies. It might mean that you're putting too much into one module. Perhaps make smaller, more specialised, modules. Without seeing more explicit examples, it's hard to be much help here.
if i remove all "use" clauses from all of my PM's...then i have to use full sub qualifiers. for example, pm::html::get_user_friends($dbh, $uid) will use security to determine if a friend is a banned user or not (banned is part of security)
You're misunderstanding things here.
Calling use does two things. Firstly, it loads the module and secondly, it runs the module's import() subroutine. And it's the import() subroutine that does all of the Exporter.pm magic. And it's the Exporter.pm magic that allows you to call subroutines from other modules using short names rather than fully-qualified names.
So, yes, if you remove use statements from a module, then you will probably lose the ability to use short names for subroutines from other modules. But you're also relying on some other code in your program to actually load the module. So if you remove all use statements that load a particular module, then you won't be able to call the subroutines from that module. Which seems counter-productive.
It's generally a very good idea for all code (whether it's your main calling program or a module) to explicitly load (with use) any modules that it needs. Perl keeps track of modules that have already been loaded, so there is no problem with inefficiency due to modules being loaded multiple times. If you want to load a module and turn off any exporting of symbol names, then you can do that using syntax like:
use Some::Module (); # turn off exports
The rest of your question just seems like a rant. I can't find any more questions to answer.

Determine where Moose attributes and methods were inherited from?

I often work on a huge, not-very-well-documented, object-oriented Perl repo at my place of employment. While maintaining the code, I frequently need to trace things that are inherited from other classes so that I can understand what they're doing. For example, I need to figure out what $self->mystery is and what it's doing:
package Foo::Bar;
use Moose;
use Method::Signatures;
use Foo::Bar::Element;
use Foo::Bar::Function;
use base qw (Baz::Foo::Bar);
method do_stuff ($some_arg) {
# mystery is not defined in Foo::Bar
my $mystery = $self->mystery;
$mystery->another_mystery($some_arg);
}
I usually find myself spending way too much time tracing through parent classes. So my question is, is there an easy way for me to figure out where $self->mystery comes from? Or in other words, I need to find where mystery is declared.
And by "easy way", I don't mean using ack or grep to string search through files. I'm hoping there's some sort of debugging module I can install and use which could help give me some insight.
Thank you.
Thanks to Standard Perl . . . the comes_from Method!
You don’t need to download any special tool or module this, let alone some giant IDE because your undocumented class structure has gotten too complicated for mere humans ever to understand without a hulking IDE.
Why not? Simple: Standard Perl contains everything you need to get the answer you’re looking for. The easy way to find out where something comes from is to use the very useful comes_from method:
$origin = $self->comes_from("mystery");
$secret_origin = $self->comes_from("another_mystery");
$birthplace = Some::Class->comes_from("method_name");
That will return the original name of the subroutine which that method would resolve to. As you see, comes_from works as both an object method and a class method, just like can and isa.
Note that when I say the name of the subroutine it resolves to, I mean where that subroutine was originally created, back before any importing or inheritance. For example, this code:
use v5.10.1;
use Path::Router;
my($what, $method) = qw(Path::Router dump);
say "$what->$method is really ", $what->comes_from($method);
prints out:
Path::Router->dump is really Moose::Object::dump
Similar calls would also reveal things like:
Net::SMTP->mail is really Net::SMTP::mail
Net::SMTP->status is really Net::Cmd::status
Net::SMTP->error is really IO::Handle::error
It works just fine on plain ole subroutines, too:
SQL::Translator::Parser::Storable->normalize_name
is really SQL::Translator::Utils::normalize_name
The lovely comes_from method isn’t quite built in though it requires nothing outside of Standard Perl. To make it accessible to you and all your classes and objects and more, just add this bit of code somewhere — anywhere you please really :)
sub UNIVERSAL::comes_from($$) {
require B;
my($invocant, $invoke) = #_;
my $coderef = $invocant->can($invoke) || return;
my $cv = B::svref_2object($coderef);
return unless $cv->isa("B::CV");
my $gv = $cv->GV;
return if $gv->isa("B::SPECIAL");
my $subname = $gv->NAME;
my $packname = $gv->STASH->NAME;
return $packname . "::" . $subname;
}
By declaring that as a UNIVERSAL sub, now everybody who’s anybody gets to play with it, just like they do with can and isa. Enjoy!
Are you sure you don't want an IDE? It seems to be what you are asking about. Padre, Eclipse EPIC, Emacs , and vim and many other editors offer some variation on the features you mention - probably simpler than you seem to want. If you have big project to navigate ctags can help - it's usually easy to integrate into an editor and you are allowed to hack on your configuration file (with regexes BTW) to get it to recognize bits of a complicated set of source files.
There is a related PERL FAQ entry about IDEs and a SO question: What's a good development environment for Perl?. There are also a host of CPAN modules you will want to use when developing that let you look into your code programmatically:
Devel::Kit
Devel::Peek
SUPER
Devel::Trepan
MooseX::amine / mex
...
You can see an example of a script that looks for methods in classes in the SO node: Get all methods and/or properties in a given Perl class or module.
You might be able to get tools like these to help you hop around in your source in a way you find useful from a shell or from inside the debugger. Trepan has a good short summary of debugging tools as part of its documentation. Generally though you can be very productive combining Data::Dumper the B:: modules (B::Xref , B::Deparse, etc., etc.) with the debugger and ack.

use symbols from module without package (require)

I already asked a similar question, but it had more to do with using barewords for functions. Basically, I am refactoring some of my code as I have begun learning about "package" and OOP in perl. Since none of my modules used "package" I could just "require" them into my code, and I was able to use their variables and functions without any trouble. But now I have created a module that I will be using as a class for object manipulation, and I want to continue being able to use my functions in other modules in the same way. No amount of reading docs and tutorials has quite answered my question, so please, if someone can offer an explanation of how it works, and why, that would go a really long way, more than a "this is how you do it"-type answer.
Maybe this can illustrate the problem:
myfile.cgi:
require 'common.pm'
&func_c('hi');
print $done;
common.pm:
$done = "bye";
sub func_c {print #_;}
will print "hi" then "bye", as expected.
myfile_obj.cgi:
use common_obj;
&func_obj('hi');
&finish;
common_obj.pm:
package common_obj;
require 'common.pm';
sub func_obj {&func_c(#_);}
sub finish {print $done;}
gives "Undefined subroutine func_c ..."
I know (a bit) about namespaces and so on, but I don't know how to achieve the result I want (to get func_obj to be able to call func_c from common.pm) without having to modify common.pm (which might break a bunch of other modules and scripts that depend on it working the way it is). I know about use being called as a "require" in BEGIN along with its import().. but again, that would require modifying common.pm. Is what I want to accomplish even possible?
You'll want to export the symbols from package common_obj (which isn't a class package as it stands).
You'll want to get acquainted with the Exporter module. There's an introduction in Modern Perl too (freely available book, but consider buying it too).
It's fairly simple to do - if you list functions in #EXPORT_OK then they can be made available to someone who uses your package. You can also group functions together into named groups via EXPORT_TAGS.
Start by just exporting a couple of functions, list those in your use statement and get the basics. It's easy enough then.
If your module was really object-oriented then you'd access the methods through an object reference $my_obj->some_method(123) so exporting isn't necessary. It's even possible for one package to offer both procedural/functional and object-oriented interfaces.
Your idea of wrapping old "unsafe" modules with something neater seems a sensible way to proceed by the way. Get things under control without breaking existing working code.
Edit : explanation.
If you require a piece of unqualified code then its definitions will end up in the requiring package (common_obj) but if you restrict code inside a package definition and then use it you need to explicitly export definitions.
You can use common_obj::func_obj and common_obj::finish. You just need to add their namespaces and it will work. You don't need the '&' in this case.
When you used the package statement (in common_obj.pm) you changed the namespace for the ensuing functions. When you didn't (in common.pm) you included the functions in the same namespace (main or common_obj). I don't believe this has anything to do with use/require.
You should use Exporter. Change common_obj to add:
use base Exporter;
#EXPORT_OK = qw/func_obj finish/;
Then change myfile_obj:
use common_obj qw/func_obj finish/;
I am assuming you are just trying to add a new interface into an old "just works" module. I am sure this is fraught with problems but if it can be done this is one way to do it.
It's very good that you're making the move to use packages as that will help you a lot in the future. To get there, i suggest that you start refactoring your old code as well. I can understand not wanting to have to touch any of the old cgi files, and agree with that choice for now. But you will need to edit some of your included modules to get where you want to be.
Using your example as a baseline the goal is to leave myfile.cgi and all files like it as they are without changes, but everything else is fair game.
Step 1 - Create a new package to contain the functions and variables in common.pm
common.pm needs to be a package, but you can't make it so without effecting your old code. The workaround for this is to create a completely new package to contain all the functions and variables in the old file. This is also a good opportunity to create a better naming convention for all of your current and to be created packages. I'm going to assume that maybe you don't have it named as common.pm, but regardless, you should pick a directory and name that bits your project. I'm going to randomly choose the name MyProject::Core for the functions and variables previously held in common.pm
package MyProject::Core;
#EXPORT = qw();
#EXPORT_OK = qw($done func_c);
%EXPORT_TAGS = (all => [#EXPORT, #EXPORT_OK]);
use strict;
use warnings;
our $done = "bye";
sub func_c {
print #_, "\n";
}
1;
__END__
This new package should be placed in MyProject/Core.pm. You will need to include all variables and functions that you want exported in the EXPORT_OK list. Also, as a small note, I've added return characters to all of the print statements in your example just to make testing easier.
Secondly, edit your common.pm file to contain just the following:
use MyProject::Core qw(:all);
1;
__END__
Your myfile.cgi should work the same as it always does now. Confirm this before proceeding.
Next you can start creating your new packages that will rely on the functions and variables that used to be in the old common.pm. Your example common_obj.pm could be recoded to the following:
package common_obj;
use MyProject::Core qw($done func_c);
use base Exporter;
#EXPORT_OK = qw(func_obj finish);
use strict;
use warnings;
sub func_obj {func_c(#_);}
sub finish {print "$done\n";}
1;
__END__
Finally, myfile_obj.cgi is then recoded as the so:
use common_obj qw(func_obj finish);
use strict;
use warnings;
func_obj('hi');
finish();
1;
__END__
Now, I could've used #EXPORT instead of #EXPORT_OK to automatically export all the available functions and variables, but it's much better practice to only selectively import those functions you actually need. This method also makes your code more self-documenting, so someone looking at any file, can search to see where a particular function came from.
Hopefully, this helps you get on your way to better coding practices. It can take a long time to refactor old code, but it's definitely a worthwhile practice to constantly be updating ones skills and tools.

How best to override/wrap core functions like sysread when they are called in another package

I'm working on a fairly complex application written in Perl. I'm fairly experienced with the language, but I'm just stumped on this.
I'm using a module, Foo, which uses sysread and syswrite for various operations on a file-handle (a bi-directional socket, in this case) that I pass to its constructor.
I want to do the following: From another module I am writing, (let's call it Bar), I want to change the way that sysread/write behave only when called from within methods that belong to Foo
Sysread et al need to work as normal everywhere else. It can be safely assumed that the use of sysread will not change in Foo.
The reason I want to do this is that I need to track the number of bytes being read from/written to the afore-mentioned file handle. At this point, this seems like the only way I can get this information - basically saving the return value from sysread/write.
I have no problems using anything from the CPAN, as long as it's of good quality.
Update: I found a better solution to my specific problem, and have posted the code here:
https://github.com/Hercynium/Tie-Handle-CountChars
It seems to be working very well in my application, but I won't be posting it to the CPAN until I've more thoroughly tested it, plus written some actual unit tests :)
You could do this by creating your own Foo::sysread function, which wraps the core function by logging the return value. The wrapping can be done automatically (preventing you from having to mess about with the symbol table yourself) with Class::Method::Modifiers:
package Foo;
use strict;
use warnings;
# ... other code...
use Class::Method::Modifiers;
around sysread => sub {
my $orig = shift;
my $return = CORE::sysread(#_);
# do something with $return
return $return;
};

How can I use NYTProf in a library

I'm wondering if Devel::NYTProf can be used as a library in another library. I'd like to do something like the following
around 'somesub' => sub {
my $orig = shift;
my $self = shift;
start-timing;
$self->$orig(#_);
end-timing;
print '$time';
}
but from it's documentation I'm unable to determine if it can be used like this. Is it possible? could someone tell me the API calls that i'd do?
The simplest, most reliable thing to do is:
Add DB::enable_profile and DB::disable_profile calls in your library (you might want to check whether the subs are defined first, to avoid breakage when NYTProf isn't loaded).
Start perl with -d:NYTProf and NYTPROF=start=no in the environment.
All of this is pretty clearly explained in the Devel::NYTProf docs.
You could try having your library conditionally load NYTProf, but the deal here is that only stuff compiled after NYTProf is loaded gets any tracepoints. That might sound perfectly okay, since you only want to profile your library, but it's not clear what will happen if your library calls out (or calls back) to any other code, and I didn't test it. It's probably a lot easier to make the simple version make do :)
I don't think it can be used that way. But you might take a look at Aspect::Library::Profiler or Aspect::Library::Timer