2

I am trying to bless a string variable -- demonstrated in the code below. Bless only seems to work when I use a hash or array. Are you allowed to bless strings? If no, what can you bless? I have been debugging for a while, any help would be greatly appreciated. :-) If I making an error in my code please let me know what it is.

This is a perl file. The code is not finished, but it never reaches the "Page End" statement. So I have ceased to lengthen it. $FileInfo is an array define earlier read from a file but due to syntax gets garbled here.

here is the call to build ojbect reference

$page = new GeneratePages(0);

package GeneratePages;  
sub new  
{  
    my $class = shift;  
    my $pageContents = $FileInfo[shift];  
    bless $pageContents, $class;  
    return $pageContents;  
}
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
rubixibuc
  • 7,111
  • 18
  • 59
  • 98
  • 2
    Please don't use Indirect Object Notation ($page = new GeneratePages(0)). There's a good chance it will bite you at some point in the future. Instead, use $page = GeneratePages->new(0). – Dave Cross Mar 31 '11 at 11:19

1 Answers1

11

Bless only works on references. From perldoc bless:

This function tells the thingy referenced by REF that it is now an object in the CLASSNAME package.

So if you want to use a string as an object, you should pass a reference to it to bless:

my $s = "foo"; # $s is a scalar variable
my $o = bless \$s, $class; # $s is now an object in the $class package
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 2
    More properly, \$s is the object, $s is the object contents. – ysth Mar 31 '11 at 09:29
  • Nit: `bless` works on any variable, but it takes a reference to the variable to bless as its argument. For example, the following prints "`Foo`": `perl -E'my $x; my $y=\$x; my $z=\$x; bless($y, "Foo"); say ref $z'` – ikegami Mar 31 '11 at 19:24
  • 4
    @ysth, The documentation for `bless` disagrees -- it calls the referenced variable the object. Furthermore, if the reference is the object, then `\${ \$s }` would create a new object and that makes no sense. Finally, the class is *not* associated with the reference, but rather the referenced variable. – ikegami Mar 31 '11 at 19:31
  • 1
    @ikegami: when you pass an object to a subroutine, what do you pass? – ysth Apr 01 '11 at 00:05
  • @ysth, I pass a reference to the object, just like I do when I want to pass an array. I would *say* I pass an object (or an array), because I don't have a problem calling the ref an object (or an array). The problem I have is with your correction that `$s` isn't the object. – ikegami Apr 01 '11 at 01:12
  • Correcting my correction, then: "more colloquially, \$s is the object" – ysth Apr 01 '11 at 03:10