Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Below you will your code without an <em>explicit</em> package for the logging functions. I've renamed LogFuncs::compile to logerr:setup to be a bit more explicit and not pollute the main namespace. Everything in perl has a package, it's just <strong>main</strong> by default. I think the code you have before, with a package for the logging functions was actually cleaner, and lends itself to being split into a separate module easily, so it can be reused easier.</p> <p>As for not understanding how the code works, I'm not sure how to address that, but only because you didn't identify any specifics of what you didn't understand. I'll assume you meant the packages. Perl packages can be viewed as namespaces, or classes. In the case of the LogFuncs package, you are using it as a namespace, and subs created in it are accessed as <strong>static class methods</strong> (to use some notation from other more traditional OO languages that may shine light on this). Package FooObj and BarObj are used more traditionally as objects by providing a constructor <strong>new()</strong>, and expecting subs within them to be called using object notation (->sub), automatically passing the object itself as the first parameter to the sub/method. The only thing defining a sub as a static class method or a object method is whether it expects to receive the object as the first parameter. As such, a little forethought and careful programming can produce subs that work for both, by correctly determining what the first passed parameter is and acting accordingly.</p> <pre><code>#! /usr/bin/perl -w use strict; use Getopt::Long; 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 logerr_setup { 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 main::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(); main::logerr($self); } } my $do_logging = 0; GetOptions( "do_logging" =&gt; \$do_logging, ); logerr_setup(do_logging =&gt; $do_logging); my $bar = BarObj-&gt;new(); logerr("Created $bar"); $bar-&gt;bar_work(); </code></pre>
 

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