I have a module named macros.rs which contains
/// Macro to easily implement FromError.
/// from_error!(MyError, IoError, MyError::IoError)
macro_rules! from_error {
( $t:ty, $err:ty, $name:path ) => {
use std;
impl std::error::FromError<$err> for $t {
fn from_error(err: $err) -> $t {
$name(err)
}
}
}
}
In my main.rs I import the module like this
#[macro_use] mod macros;
When I try to use from_error in other modules of my project, the compiler says error: macro undefined: 'from_error!'.
Turns out that the order in which you declare modules matters.
mod json; // json uses macros from the "macros" module. can't find them.
#[macro_use]
mod macros;
#[macro_use]
mod macros;
mod json; // json uses macros from the "macros" module. everything's ok this way.
Related
I've got a Perl script that I'm trying to make compatible with two different Perl environments. To work around the two different versions of Socket I have, I'm doing a little hackery with require and import. I've got it working, but I'm not happy with the behavior.
Mod.pm:
package Mod;
use base 'Exporter';
our #EXPORT = qw( MAGIC_CONST );
sub MAGIC_CONST() { 42; }
test.pl:
use Mod;
#require Mod;
#import Mod;
printf "MAGIC_CONST = ". MAGIC_CONST ."\n";
printf "MAGIC_CONST = ". MAGIC_CONST() ."\n";
Outputs:
MAGIC_CONST = 42
MAGIC_CONST = 42
But using the 'require' and 'import' instead, I get this:
Output:
MAGIC_CONST = MAGIC_CONST
MAGIC_CONST = 42
So the question is: Is there a clean way I can get the normal behavior of the constants? I can certainly do sub MAGIC_CONST { Mod::MAGIC_CONST(); } but that's pretty ugly.
What I'm actually doing is something like this:
use Socket;
if ($Socket::VERSION > 1.96) {
import Socket qw(SO_KEEPALIVE); # among others
setsockopt($s, SOL_SOCKET, SO_KEEPALIVE); # among others
}
The reason the require version prints MAGIC_CONST instead of 42 is because use is what tells perl to import the symbols from one module to another. Without the use, there is no function called MAGIC_CONST defined, so perl interprets it as a string instead. You should use strict to disable the automatic conversion of barewords like that into strings.
#!/usr/bin/env perl
no strict;
# forgot to define constant MAGIC_CONST...
print 'Not strict:' . MAGIC_CONST . "\n";
produces
Not strict:MAGIC_CONST
But
#!/usr/bin/env perl
use strict;
# forgot to define constant MAGIC_CONST...
print 'Strict:' . MAGIC_CONST . "\n";
Produces an error:
Bareword "MAGIC_CONST" not allowed while "strict subs" in use at
./test.pl line 4. Execution of ./test.pl aborted due to compilation
errors.
So if you want to use one module's functions in another, you either have to import them with use, or call them with the full package name:
package Foo;
sub MAGIC_CONST { 42 };
package Bar;
print 'Foo from Bar: ' . Foo::MAGIC_CONST . "\n";
Foo from Bar: 42
It's usually best to avoid conditionally importing things. You could resolve your problem as follows:
use Socket;
if ($Socket::VERSION > 1.96) {
setsockopt($s, SOL_SOCKET, Socket::SO_KEEPALIVE);
}
If you truly want to import, you still need to do it at compile-time.
use Socket;
use constant qw( );
BEGIN {
if ($Socket::VERSION > 1.96) {
Socket->import(qw( SO_KEEPALIVE ));
} else {
constant->import({ SO_KEEPALIVE => undef });
}
}
setsockopt($s, SOL_SOCKET, SO_KEEPALIVE) if defined(SO_KEEPALIVE);
Adam's answer gives a good explanation of what is going on and how to get the desired behavior. I am going to recommend not using constant.pm to define symbolic names for constants. A fairly nice looking and convenient alternative with fewer gotchas is to use constants defined using Const::Fast and allow them to be imported.
In addition, by using Importer in the module which wants to import the constants, the module that defines the constants can avoid inheriting Exporter's heavy baggage, or having to use Exporter's import.
The fact that Const::Fast allows you to define real constant arrays and hashes is a bonus.
For example:
package MyConstants;
use strict;
use warnings;
use Const::Fast;
use Socket;
const our #EXPORT => ();
const our #EXPORT_OK => qw(
%SOCKET_OPT
);
const our %SOCKET_OPT => (
keep_alive => ($Socket::VERSION > 1.96) ? Socket::SO_KEEPALIVE : undef,
);
__PACKAGE__;
__END__
Using these constants in a script:
#!/usr/bin/env perl
use strict;
use warnings;
use Socket;
use Importer 'MyConstants' => qw( %SOCKET_OPT );
if ( defined $SOCKET_OPT{keep_alive} ) {
setsockopt($s, SOL_SOCKET, $SOCKET_OPT{keep_alive});
}
As I note in my blog post:
f I want to read the constants from a configuration file, that's trivial. If I want to export them to JSON, YAML, INI, or whatever else, that's also trivial. I can interpolate them willy-nilly.
For those who have taken seriously Exporter's stance against exporting variables, this takes some getting used to. Keep in mind that the admonition is there to make sure you don't write code that willy nilly modifies global variables. However, in this case, the variables we are exporting are not modifiable. Maybe you can convince yourself that the concern really does not apply in this instance. If you try to refer to a non-existent constant, you get an error (albeit during run time) ...
In most cases, the benefits of this approach outweigh the speed penalty of not using constant.pm.
Given the following:
package My::Pack;
use Exporter::Easy (
OK => [ qw(pack_func) ],
);
sub pack_func {
...
}
package main;
<script here that uses pack_func>
How do I import the symbol I want?
use doesn't work since it's looking for another file to open.
require doesn't support the syntax that use does for specifying the symbols you want.
Are my only choices to say My::Pac::pack_func() in the script or import the symbol manually through typeglob assignmnet?
The statement:
use Some::Module qw(foo bar);
is exactly equivalent to:
BEGIN {
require Some::Module;
Some::Module->import( qw(foo bar) );
}
in your case, the code for the My::Pack module has already been loaded, so you don't need to require it. Thus, you can just do:
BEGIN { My::Pack->import( qw(pack_func) ) }
Test::More provides the commonly-used use_ok test to test that a module loads properly. But how do I test that a module fails to load? Test::Exception offers dies_ok and cousins for similar failures, but not at use-time.
This is useful when a module requires specific parameters or a specific environment to load properly, and I want to test for these conditions. As an example, perhaps my 'Foo' module requires a configuration parameter, and should fail to load otherwise:
use Foo 'eat my hat'; # This should work
use Foo; # This should die
I can easily test the first case with Test::More:
BEGIN { use_ok('Foo','eat my hat') }
But how can I test the other?
BEGIN { use_not_ok('Foo') } # use_not_ok doesn't exist
use Foo;
is
BEGIN { require Foo; import Foo; }
so
BEGIN { ok(!eval { require Foo; import Foo; 1 }); }
But I'd just go with
BEGIN { ok(!eval('use Foo; 1')); }
I'm not thinking too clearly right now and possibly overlooking something simple. I've been thinking about this for a while and been searching, but can't really think of any sensible search queries anymore that would lead me to what i seek.
In short, I'm wondering how to do module inheritance, in the way base.pm/parent.pm do it for object-oriented modules; only for Exporter-based modules.
A hypothetical example of what i mean:
Here's our script. It originally loaded Foo.pm and called baz() from it, but baz() has a terrible bug (as we'll soon see), so we're using Local/Patched/Foo.pm now which should fix the bug. We're doing this, because in this hypothetical case we cannot change Foo (it is a cpan module under active development, you see), and it is huge (seriously).
#!/usr/bin/perl
# use Foo qw( baz [... 100 more functions here ...] );
use Local::Patched::Foo qw( baz [... 100 more functions here ...] );
baz();
Here's Foo.pm. As you can see, it exports baz(), which calls qux, which has a terrible bug, causing things to crash. We want to keep baz and the rest of Foo.pm though, without doing a ton of copy-paste, especially since they might change later on, due to Foo still being in development.
package Foo;
use parent 'Exporter';
our #EXPORT = qw( baz [... 100 more functions here ...] );
sub baz { qux(); }
sub qux { print 1/0; } # !!!!!!!!!!!!!
[... 100 more functions here ...]
1;
Lastly, since Foo.pm is used in MANY places, we do not want to use Sub::Exporter, as that would mean copy-pasting a bandaid fix to all those many places. Instead we're trying to create a new module that acts and looks like Foo.pm, and indeed loads 99% of its functionality still from Foo.pm and just replaces the ugly qux sub with a better one.
What follows is what such a thing would look like if Foo.pm was object-oriented:
package Local::Patched::Foo;
use parent 'Foo';
sub qux { print 2; }
1;
Now this obviously will not work in our current case, since parent.pm just doesn't do this kinda thing.
Is there a clean and simple method to write Local/Patched/Foo.pm (using any applicable CPAN modules) in a way that would work, short of copying Foo.pm's function namespace manually?
If it's one subroutine you want to override, you can do some monkey patching:
*Foo::qux = \&fixed_qux;
I'm not sure if this is the cleanest or best solution, but for a temporary stopgap until upstream fixes the bug in qux, it should do.
Just adding in yet another way to monkey-patch Foo's qux function, this one without any manual typeglob manipulation.
package Local::Patched::Foo;
use Foo (); # load but import nothing
sub Foo::qux {
print "good qux";
}
This works because Perl's packages are always mutable, and so long as the above code appears after loading Foo.pm, it will override the existing baz routine. You might also need no warnings 'redefine'; to silence any warnings.
Then to use it:
use Local::Patched::Foo;
use Foo qw( baz );
baz(); # calls the patched qux() routine
You could do away with the two use lines by writing a custom import method in Local::Patched::Foo as follows:
# in the Local::Patched::Foo package:
sub import {
return unless #_; # return if no imports
splice #_, 0, 1, 'Foo'; # change 'Local::Patched::Foo' to 'Foo'
goto &{ Foo->can('import') }; # jump to Foo's import method
}
And then it is just:
use Local::Patched::Foo qw( baz );
baz(); # calls the patched qux()
Rather than hijacking Alexandr's answer (which was correct, but incomplete), here's a solution under separate copy:
package Foo;
use Exporter 'import';
our #EXPORT = qw(foo bar baz qux);
our %EXPORT_TAGS = (
'all' => [ qw(foo bar baz qux) ],
'all_without_qux' => [ qw(foo bar baz) ],
);
sub foo { 'foo' }
sub bar { 'bar' }
sub baz { 'baz' }
sub qux { 'qux' }
1;
package Foo::Patched;
use Foo qw(:all_without_qux);
use Exporter 'import';
our #EXPORT = qw( foo bar baz qux );
sub qux { 'patched qux' }
1;
package main;
use Foo::Patched;
print qux();
You can also use Foo; in your program, as long as you use it before Foo::Patched, or you will overwrite the patched qux with the original broken version.
There are a few morals here (at least they are IMHO):
don't export into the caller's namespace without being explicitly told to (i.e. keep #EXPORT empty, and use #EXPORT_OK and %EXPORT_TAGS to allow the caller to specify exactly what they want. Or alternatively, don't export at all, and use fully-qualified names for all library functions.
Write your libraries so that the functions are called OO-style: Foo->function rather than Foo::function. This makes it much easier to override a function by using the standard use base syntax we all know and love, without having to mess around with monkeypatching symbol tables or manipulating exporter lists.
One approach is to simply replace the sub reference. if you can install it, use the Sub::Override CPAN module. Absent that, this will do:
package Local::Patched::Foo;
use Exporter;
sub baz { print "GOOD baz!\n" };
sub import() {
*Foo::baz = \&Local::Patched::Foo::baz;
}
1;
package Local::Patched::Foo;
use Foo qw/:all_without_qux/; #see Exporter docs for tags or just list all functions
use Exporter 'import'; #modern way
our #EXPORT = qw( baz [... 100 more functions here ...] qux);
sub qux { print 2; }
1;
I would suggest that you replace the offending file.
mkdir Something
cp Something.pm Something/Legacy.pm # ( or /Old.pm or /Bad.pm )
And then go in to that file and edit the package line:
package Something::Legacy;
Then you have a place to step in front of the legacy code. Create a new Something.pm and get all it's exports:
use Something::Legacy qw<:all>;
our #EXPORT = #Something::Legacy::EXPORT;
our #EXPORT_OK = #Something::Legacy::EXPORT_OK;
our %EXPORT_TAGS = %Something::Legacy::EXPORT_TAGS;
After you have all that in your current package, just re-implement the sub.
sub bad_thing { ... }
Anything your legacy code that calls Something::do_something will be calling the old code via the new module. Any legacy code calling Something::bad_thing will be calling the new code.
As well, you can manipulate *Something::Legacy in other ways. If your code does not uses a local call, you're going to have to clobber &Something::Legacy::bad_thing.
my $old_bad_thing = \&Something::Legacy::bad_thing;
*Something::Legacy::bad_thing = \&bad_thing;
Thus bad_thing is still allowed to use that behavior, if desired:
sub bad_thing {
...
eval {
$old_bad_thing->( #_ );
};
unless ( $EVAL_ERROR =~ /$hinky_message/ ) {
...
}
...
}
module foo/bar.pm
package foo::bar;
stuff
stuff
package foo::wizzy;
require Exporter;
our #ISA=qw(Exporter);
our #EXPORT=qw(x);
use constant
{
x=>1
};
a consumer that does
use Foo::bar;
does not get the foo::wizzy::x export
I know I can make it two separate modules, but still I should be able to make this work, shouldn't I?
You can do it using Exporter's export_to_level method to have the "main package" re-export the "other" package's symbols like so:
sub import {
my $self = shift;
$self->export_to_level(1, #_);
Some::Other::Module->export_to_level(1);
}
though if Some::Other::Module does something more complicated than "export everything" you will probably need fancier handling for #_.
I really have to ask why, though—I can't imagine a use for this that's compatible with the words "good code" :)
When you call use foo::bar, what actually happens is essentially:
BEGIN {
require foo::bar;
foo::bar->import;
}
(see perldoc -f use)
So import is never getting called on foo::wizzy. If you want to import those symbols as well, you can call BEGIN { foo::wizzy->import } yourself (after use foo::bar). Or, as you said, just split these two packages into separate files, which would be much more human-readable.
(By the way, it's not advisable to use lower-cased package names, as those are generally reserved for perl pragmata.)
At the end of the module, put:
BEGIN { $INC{'foo/wizzy.pm'} = 1 }
Then code can just say:
use foo::bar;
use foo::wizzy;
to get foo::wizzy's exports.
First off, I find it helpful to use enclosing braces to control scope when cramming multiple packages into one file. Also, enclosing the package in a BEGIN block makes it work more like a proper use was used to load it, but this is mostly if I am cramming the package into the main script.
use Foo is the same as BEGIN { require Foo; Foo->import }.
So, you have two choices:
call BEGIN{ Foo::Whizzy->import; } in your main script.
make Foo::Bar::import trigger Foo::Whizzy::import on the calling module.
In Foo/Bar.pm:
{ package Foo::Bar;
use Exporter qw( export_to_level );
# Special custom import. Not needed if you call Foo::Whizzy->import
sub import {
shift;
export_to_level('Foo::Whizzy', 1, #_ );
}
# stuff
# stuff
}
{ package Foo::Whizzy;
require Exporter;
our #ISA=qw(Exporter);
our #EXPORT=qw(x);
use constant { x=>1 };
}
1; # return true
In your main code:
use Foo::Bar;
# If you don't do a custom import for Foo::Bar, add this line:
BEGIN { Foo::Whizzy->import };