in reply to Create an array reference from a string

I think that you may have made a bad choice of string value for $foo in that some other posters think that you want to interpolate the value of $bar. Is it the case that you want two distinct and possibly unrelated values for $foo, one a string and the other an array reference? If so, I would suggest that you might have a design flaw somewhere (which a hash solution might fix), but on the off chance that you really need this, you could use overload -- though I wouldn't recommend it.

#!/usr/local/bin/perl -w use strict; + package ArrayOrString; use overload '""' => \&to_string; + my $STRING_VAL = ''; + sub new { my ($class, $arrayref) = @_; die "not an array ref" unless 'ARRAY' eq ref $arrayref; bless $arrayref, $class; } + sub string { shift; $STRING_VAL = shift if @_; return $STRING_VAL; } + sub to_string { return $STRING_VAL; } + package main; + my @bar = qw(one two three); my $foo = ArrayOrString->new(\@bar); $foo->string('bar'); print "*** $foo ***\n"; + foreach my $baz (@$foo) { print "Val: $baz \n"; }

Update: Whoops! I see your reply to dragonchild. You want soft references and that's a bad idea. Ignore my neat code, it doesn't do what you want, though it does what I said it does :)

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re: Re: Create an array reference from a string
by xorl (Deacon) on Apr 13, 2004 at 13:16 UTC
    This is Cool, Ovid. I wish I could give more than just a ++ to your answer. Thanks.