On 02/20/04 01:35, Jacob Chapa wrote:

what does bless do?

It depends on how much you know. ;-)


Basically it takes a reference to a perl type and tags it as an object, so that in addition to being a reference to a type, it now has special properties: primarily that it can have subroutines (methods) associated with it. It's a reference on steroids.

my $href = \%ahash;

$href is a reference to a hash. The only thing you can do is store (key, value) pairs:

$href->{key} = 'value';

and access the values:

print $href->{key};

The 'bless' operator takes that reference and tags it as something special; something that has extra features.

my $blessed_ref = bless $href;

Now we have a blessed reference. We can use it a reference just like before:

print $blessed_ref->{key};

but now it also has some special properties; one of which allows us to associate subroutines with the reference:

sub say_hello { print "Hello, World!\n"; }
$blessed_ref->say_hello();

Here we define a subroutine that will be associated with the subroutine (because it's in the same package). Then we can invoke that subroutine through the reference (a subroutine invoked through a reference is called a method).

When a subroutine is invoked through a blessed reference it gets that blessed reference passed as the first argument. For example:

(Note: If your not familiar with the Data::Dumper module, it is a very usefull module that lets you look at the structure of any data type.)

use Data::Dumper;
print Dumper($blessed_ref);

This shows the structure of our blessed reference. Now:

sub show_args { print Dumper([EMAIL PROTECTED]); }
$blessed_ref->show_args();

This shows an array with one element that has the same value as our blessed reference above. If we call that same subroutine without invoking it through the reference:

show_args();

We see that the result is an empty array.

The value of having this blessed reference passed to our methods is that we can store state data that can be used amoung different subroutines and from one invokation to the next. For example:

sub inc {
  my $self = shift;
  return ++$self->{counter};
}

for (1..5) { print $blessed_ref->inc() . "\n"; }

will print out:
1
2
3
4
5

The bless operator also takes another argument which I've ignored until now because it will use as a default the name of the current package. In some of the examples above where we used Data::Dumper you may have noticed this argument which is 'main' since the default package when none is specified is 'main'. This is the name used for the class of your blessed reference.

This is pretty much where the documentation picks up, so I'll shut up now. Sorry to be so verbose.

Regards,
Randy.

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to