Hello David,

I am looking for a class that stores zero or more items (e.g. a list)
and that provides accessors that accept and return scalar, list, and/or
array references depending upon context and object content (similar to
CGI.pm, but not exactly the same):

The `wantarray` function can be made use of. It helps in determining the context.

#!/usr/bin/perl

use strict;
use warnings;

package WishfulThinkingListClass;

sub new {
    return bless [], __PACKAGE__;
}

sub set {
    my ( $self, @values ) = @_;
    @$self = @values;

    return;
}

sub get {
    my $self = shift;

    if (wantarray) {
        return @$self;
    }
    else {
        if ( @$self > 1 ) {
            return [@$self];
        }
        return $self->[0];
    }
}

package main;

use Test::More 'tests' => 4;

my $obj = WishfulThinkingListClass->new();

$obj->set('foo');
my $value = $obj->get();
is( $value, 'foo', '$value = foo' );

my @values = $obj->get();
ok( eq_array( \@values, ['foo'] ), '@values = (foo)' );

$obj->set( 'bar', 'baz' );
$value = $obj->get();
ok( eq_array( $value, [ 'bar', 'baz' ] ), '$value = [ "bar", "baz" ]' );

@values = $obj->get();
ok( eq_array( \@values, [ 'bar', 'baz' ] ), '@values = ( "bar", "baz" )' );

__END__

Regards,
Alan Haggai Alavi.
--
The difference makes the difference.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to