Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Ciao monks.

I have been trying to improve my perl skills for a few months and one area I don't understand is the 'tie' function.

package Queue; use warnings; use strict; sub TIESCALAR { my $class = shift; my @data = split ' ', $_[0]; bless( \@data, $class ); return \@data; } sub STORE { my $obj = shift; my $data = shift; push @$obj, $data; } sub FETCH { my $obj = shift; return shift( @$obj ); } return 1;

use warnings; use strict; use Queue; my $line; tie( $line, 'Queue', 'a b c d' ); print $line, "\n"; print $line, "\n"; print $line, "\n";

Output:
C:\Perl\bin>perl myqueue.pl a b c C:\Perl\bin>

I don't understand how this program works.
Could you please explain it to me?

Thanks,
Ciao, Alexa

Replies are listed 'Best First'.
Re: Help with the tie function.
by chunlou (Curate) on Jul 27, 2003 at 09:38 UTC

    tie( $line, 'Queue', 'a b c d' ); calls the TIESCALAR sub. First arguement my $class = shift; is 'Queue'. 'a b c d' goes into my @data  = split ' ', $_[0];.

    Whenever you "read" $line (which includes print) FETCH is called. Object reference will be passed to my $obj = shift;. @$obj in FETCH is the dereferencing of $line pointing to \@data in TIESCALAR.

    STORE kind of overloads the operator =.

Re: Help with the tie function.
by edan (Curate) on Jul 27, 2003 at 09:27 UTC

    Try entering the following at your command prompt:

    perldoc perltie

    That should give you some good info about tie.

    --
    3dan