Hi v_melnik,

Globals have a bad reputation because they are so commonly misused. But that doesn't make all globally accessible values bad: Will you ever have a need for more than one logger object in your entire application? And you can still use an OO approach and encapsulate the retrieval of the globally accessible value in a method, allowing for you to later change how loggers are retrieved (admittedly, if you make it a class method, that limits it a bit, but luckily in Perl class and instance methods are very similar). Here are just a few examples of the many possibilities:

use warnings; use strict; use feature 'state'; package Library; sub new { bless {}, shift } sub logger { # Just an example; # could be class or instance method / property, # could hand out different logger objects. state $logger = Library::Logger->new; return $logger; } package Library::Logger; sub new { bless {}, shift } sub log { shift; print "[".gmtime." UTC] @_\n" } package Library::Foo; sub new { bless {}, shift } sub foo { Library->logger->log("access via class method works") } package Library::Bar; use parent -norequire, 'Library'; sub bar { shift->logger->log("inheritance works") } package Library::Quz; sub new { my $class = shift; bless {@_}, $class } sub library { shift->{library} } sub quz { shift->library->logger->log("access via property works") } package main; Library::Foo->new->foo; Library::Bar->new->bar; my $lib = Library->new; $lib->logger->log("access via instance method works"); Library::Quz->new(library=>$lib)->quz;

Update: Added Library::Quz class and updated example code accordingly; added some comments.

Hope this helps,
-- Hauke D


In reply to Re: Passing the logger's object (updated) by haukex
in thread Passing the logger's object by v_melnik

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.