in reply to Bless a string

As the error message explains, you can only pass references to bless, so do that:

bless \$string;

(The second argument of bless defaults to __PACKAGE__, so no reason to repeat that).

Note that the blessing sticks to the string, not to the reference, so you can access the package information even if you only pass the string itself around:

$ perl -wE 'my $s = "foo"; bless \$s; say ref \$s' main

Replies are listed 'Best First'.
Re^2: Bless a string
by Sewi (Friar) on Dec 01, 2011 at 11:29 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.

      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"