Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

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 would be compiled with "use bytes" active. Alternately, if you would do:
use Foo;
in your program, then the source of 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
        die qq{Can only have one setting of "use bytes" per run of Per
         if $bytes != ($_[1] eq "usebytes"); # different setting from 
    } 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 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
Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://293290]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2018-05-22 02:45 GMT
Find Nodes?
    Voting Booth?