in reply to tie and bless - guidence needed
There is a key difference between tie and bless. tie changes the behavior of a standard Perl type. For example, when you tie a hash to the SDBM_File class, from outside the hash looks exactly the same, but behind the scenes the data is stored in a file instead of in memory.
bless, on the other hand, acts on a reference to something. With that reference, you get a whole new interface provided by the class. For example, CGI->new() calls bless and gives you back a CGI object. You can call methods on that object, like param() and header(). (You don't even have to care if the reference refers to a hash or an array or something else.)
Here's an example of tie. See how, after %hash has been tied, you still access it just like a regular hash, even though Everything in the hash is being stored on disk. The file sticks around after the program exits, so you can tie another hash to the same file with SDBM_File and access all that data again.
Here's an example of bless. Note that MyObject->new() blesses an anonymous hash reference, shifting the name of the class from @_. In the other methods, MyObject keeps data in the hash. In the main code, however, you don't need to know that MyObject is a hash under the hood.#!/usr/local/bin/perl -w use strict; use Fcntl; use SDBM_File; my %hash; tie(%hash, 'SDBM_File', 'example', O_RDWR|O_CREAT, 0640); $hash{'animal'} = 'dog'; @hash{'vegetable', 'mineral'} = ('carrot', 'quartz'); print "$hash{'animal'} is an animal.\n"; while (my($key, $val) = each %hash) { print "My $key is a $val.\n"; } __END__
That just shows the basics of these functions, which are really quite powerful and make possible lots of cool stuff. I hope this quick introduction was helpful!#!/usr/local/bin/perl -w use strict; package MyObject; sub new { return bless {}, shift; } sub get { my $self = shift; return $self->{$_[0]}; } sub set { my $self = shift; $self->{$_[0]} = $_[1]; } sub greet { print "Hello, world!\n"; } package main; my $obj = new MyObject; $obj->greet(); $obj->set('fruit', 'banana'); print $obj->get('fruit'), " is a fruit.\n"; __END__
|
|---|