Note that there are some explanatory texts on larger screens.

plurals
  1. POImporting Conditionally Compiled Functions From a Perl Module
    primarykey
    data
    text
    <p>I have a set of logging and debugging functions which I want to use across multiple modules / objects. I'd like to be able to turn them on / off globally using a command line switch.</p> <p>The following code does this, however, I would like to be able to omit the package name and keep everything in a single file.</p> <p><strong>More specifically, I would like to import the logging functions names into each module so that they can be called without any package name qualification ( similar to a C++ <code>use namespace;</code> directive ) and I want to be able to enable / disable them globally from the script which uses them as in my example code below.</strong></p> <p>This is related to two previous questions I asked, <a href="https://stackoverflow.com/questions/2460787/when-should-i-use-perls-autoload">here</a> and <a href="https://stackoverflow.com/questions/2621225/how-can-i-call-a-perl-package-i-define-in-the-same-file">here</a>.</p> <p>One other thing - I don't think I completely understand why the below code works.</p> <pre><code>#! /usr/bin/perl -w use strict; use Getopt::Long; { package LogFuncs; use threads; use Time::HiRes qw( gettimeofday ); # provide tcpdump style time stamp sub _gf_time { my ( $seconds, $microseconds ) = gettimeofday(); my @time = localtime($seconds); return sprintf( "%02d:%02d:%02d.%06ld", $time[2], $time[1], $time[0], $microseconds ); } sub logerr; sub compile { my %params = @_; *logerr = $params{do_logging} ? sub { my $msg = shift; warn _gf_time() . " Thread " . threads-&gt;tid() . ": $msg\n"; } : sub { }; } } { package FooObj; sub new { my $class = shift; bless {}, $class; }; sub foo_work { my $self = shift; # do some foo work LogFuncs::logerr($self); } } { package BarObj; sub new { my $class = shift; my $data = { fooObj =&gt; FooObj-&gt;new() }; bless $data, $class; } sub bar_work { my $self = shift; $self-&gt;{fooObj}-&gt;foo_work(); LogFuncs::logerr($self); } } my $do_logging = 0; GetOptions( "do_logging" =&gt; \$do_logging, ); LogFuncs::compile(do_logging =&gt; $do_logging); my $bar = BarObj-&gt;new(); LogFuncs::logerr("Created $bar"); $bar-&gt;bar_work(); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload