Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

External program determing "use bytes" in module

by liz (Monsignor)
on Sep 22, 2003 at 21:20 UTC ( #293290=snippet: print w/ replies, xml ) Need Help??

Description: if only blocks were avoidable... was the reason for coming up with this (possible) abomination. Slightly adapted here, with some more checks in case the same module is used from different locations with different settings.

Basically, this is a framework for a module that will either be compiled with "use bytes" or not, depending on a parameter passed (indirectly) to the import routine. This turned out rather tricky to do.

So, in your program you would either do:

use Foo qw(usebytes);
and the code of Foo.pm would be compiled with "use bytes" active. Alternately, if you would do:
use Foo;
in your program, then the source of Foo.pm would be compiled without "use bytes".

I was wondering whether this could / should be made into a generally available module and/or whether this could be applicable to other pragma's. Until I've made my mind up, I'll be leaving it here as this snippet.

package Foo;
require bytes; # make sure the module is loaded without (un)import

$bytes = 0;    # flag: whether bytes should be enforced
$evalled = 0;  # flag: whether rest of source has been compiled

sub import {
    if ($evalled++) {                   # we have evalled the rest bef
+ore
        die qq{Can only have one setting of "use bytes" per run of Per
+l\n}
         if $bytes != ($_[1] eq "usebytes"); # different setting from 
+before
    } else {                            # first time around
        $bytes = ($_[1] eq "usebytes"); # should bytes be enforced?
        local $/;                       # enable slurp mode
        eval <DATA>;                    # compile rest of source (afte
+r __DATA__)
        die $@ if $@;                   # die now if an error occurred
    }
};
1;                              # in order for require of Foo.pm to be
+ successful
__DATA__                        # actual source of module starts here
BEGIN {bytes->import if $bytes} # activate bytes if flag set
sub new { bless {},shift }      # example routine
Comment on External program determing "use bytes" in module
Download Code

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://293290]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (18)
As of 2014-12-18 09:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (48 votes), past polls