Ed am Dienstag, 11. April 2006 21.50:
> Though I'm making progress (thanks guys) I'm still having a problem
> with dereferencing the struct elements. I've re-read the section on
> References in Programming Perl and I thought what I was doing was
> correct, but I can't print out the values correctly. Here's a
> simplified version of what I'm trying to to:
Hello Ed
> use strict;
> use warnings;
> use Class::Struct;
>
> struct ( Shoppe => { # Creates a Shoppe->new() constructor.
> owner => '$', # Now owner() method accesses a scalar.
> addrs => '@', # And addrs() method accesses an array.
> stock => '%', # And stock() method accesses a hash.
> });
>
> my $store = Shoppe->new();
>
> $store->owner('Abdul Alhazred');
> $store->addrs(0, 'Miskatonic University');
> $store->addrs(1, 'Innsmouth, Mass.');
> $store->stock("books", 208);
> $store->stock("charms", 3);
> $store->stock("potions", "none");
>
>
[...]
> # dereference the hash method.
> print "stock: %{$store->stock}"; ### <---FAILS! Prints out the
> ### ref again with a % in front...
Variables starting with '%' are not interpolated in strings...
$ perl -Mstrict -Mwarnings -le 'my %h=(a=>qw{b}); print "%h";'
%h
...whereas variables starting with '@' are:
$ perl -Mstrict -Mwarnings -le 'my @a=(a=>qw{b}); print "@a";'
a b
"Workaround" (see at the end of the post for an explanation):
$ perl -Mstrict -Mwarnings -le 'my %h=(a=>qw{b}); print "@{[ %h ]}";'
a b
And since you additionally want to dereference a hash ref:
$ perl -Mstrict -Mwarnings -le 'my $href={a=>qw{b}}; print "@{[ %$href ]}";'
a b
This means, for your example:
print "stock: @{[ %{$store->stock} ]}";
[...]
> # but how do you print the store owner directly? The following fails!
It fails because $store->owner returns a scalar, and not a scalar ref that you
had to dereference:
$ perl -Mstrict -Mwarnings -le 'my $sref=\q{ab}; print "${$sref}";'
ab
The same, shortened:
$ perl -Mstrict -Mwarnings -le 'my $sref=\q{ab}; print "$$sref";'
ab
> print "owner:, ${$store->owner}";
You mean, how do you interpolate it into a string? As I mentioned in my
previous post:
print "owner: @{[ $store->owner ]}\n";
With the @{[]} construct you can interpolate everything into a string that is
a "set" of scalars (a scalar, a list, an array, a hash).
The [] provides an anonymous arrayref, and the @{} dereferences it (again).
In short,
${} and @{} are interpolated,
%{} is not.
hth!
Dani
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>