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.
In reply to Re: Create an array reference from a string
by Ovid
in thread Create an array reference from a string
by xorl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |