[Melbourne-pm] returning hashes and arrays, source filters considered harmful?

Shlomi Fish shlomif at iglu.org.il
Fri Feb 19 03:38:03 PST 2010


On Friday 19 Feb 2010 10:04:35 Jacinta Richardson wrote:
> Sam Watkins wrote:
> > Also, is there any way to make like an alias @foo
> 
> > for @$foo, so you can treat an array reference as a normal array without
> > writing @$foo all the time?  (and also for hashes)
> 
> Not in Perl 5.  Yes, in Perl 6.
> 

Actually, it is possible in Perl 5 - using tie:

-------- CODE ------

#!/usr/bin/perl

use strict;
use warnings;

package Tie::ArrayIndirect;

use base 'Tie::Array';

sub TIEARRAY
{
    my ($class, $ref) = @_;

    return bless {'ref' => $ref} , $class;
}

sub FETCH
{
    my ($self, $index) = @_;
    return $self->{'ref'}->[$index];
}

sub FETCHSIZE
{
    my ($self) = @_;

    return scalar(@{$self->{'ref'}});
}

sub STORE
{
    my ($self, $index, $val) = @_;

    return ($self->{'ref'}->[$index] = $val);
}

sub EXISTS
{
    my ($self, $index) = @_;

    return exists($self->{'ref'}->[$index]);
}

sub DELETE
{
    my ($self, $index) = @_;

    return delete($self->{'ref'}->[$index]);
}

package main;

sub return_ref
{
    return [0,1,22,303];
}

my $ref = return_ref();

my @array;

tie @array, 'Tie::ArrayIndirect', $ref;

print "array[2] = " . $array[2] . "\n";

push @array, 4444.4;

print "ref->[4] = ", $ref->[4], "\n";

----- END CODE -----

Regards,

	Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
What Makes Software Apps High Quality -  http://shlom.in/sw-quality

Deletionists delete Wikipedia articles that they consider lame.
Chuck Norris deletes deletionists whom he considers lame.

Please reply to list if it's a mailing list post - http://shlom.in/reply .


More information about the Melbourne-pm mailing list