Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^2: Bless a string

by Sewi (Friar)
on Dec 01, 2011 at 11:29 UTC ( [id://941054]=note: print w/replies, xml ) Need Help??


in reply to Re: Bless a string
in thread Bless a string

Usage of a reference is no option because too many existing files are manipulating the scalar itself.

Blessing a string is possible (done by that MongoDB module), even if I usually don't like it.

bless should always use the two-argument-form, see Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless

Replies are listed 'Best First'.
Re^3: Bless a string
by moritz (Cardinal) on Dec 01, 2011 at 12:57 UTC
    bless should always use the two-argument-form, see Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless

    Just because there's a Perl::Critic policy for something doesn't mean you should always do it that way.

    The better approach is to know what you're doing, and then make an informed decision on how you do it.

    The reason that many people recommend two-argument bless() is that your constructors work with subclassing, when you write things like sub new { my $class = shift; bless {}, $class; }.

    But when you don't use a variable as the second value, but instead a value that is known at compile time, and still hold on to the believe that code gets magially better if you use the 2-argument form of bless, you're in the realm of cargo cult programming.

    And that's not at all what "Perl Best Practices" is about -- making you think about your code is the real reason behind the book.

Re^3: Bless a string
by Eliya (Vicar) on Dec 01, 2011 at 12:49 UTC
    Usage of a reference is no option because too many existing files are manipulating the scalar itself.

    Not sure what you're saying. As moritz explicitly pointed out, it's the string (or more precisely, the SV) that's getting the blessing, not the reference. It's just that bless needs a reference as argument.

    Maybe this will convince you that the blessing is associated with the SV itself:

    $ perl -MDevel::Peek -we 'my $s = "foo"; bless \$s, "bar"; Dump $s' SV = PVMG(0x7acff0) at 0x790610 REFCNT = 1 FLAGS = (PADMY,OBJECT,POK,pPOK) IV = 0 NV = 0 PV = 0x7826d0 "foo"\0 CUR = 3 LEN = 8 STASH = 0x7877c0 "bar"

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-19 18:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found