Ed am Montag, 10. April 2006 20.56:
> I'm trying to use the Class::Struct to create some C-Like structs but
> I'm unable to dereference any array elements in the struct. I'm
> admittedly a Perl newbie trying to map my C programming experience
> into Perl so it's possible I'm "thinking in C" rathern than in Perl.
> I've referenced several texts and web references on the subject and
> get several ways to create a structure. In each case I'm unable to
> access any  elements in the structures once they are initialized.


Hello Ed,

> Here is an example taken straight out of Programming Perl (3rd ed) :

# Always a good idea, even if it compiles without use strict:
use strict;
use warnings;

> use Class::Struct;
>
> struct Manager => {         # Creates a Manager->new() constructor.
>     name    => '$',         # Now name() method accesses a scalar value.
>     salary  => '$',         # And so does salary().
>     started => '$',         # And so does started().
> };
>
> 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.
>     boss    => 'Manager',   # Initializes with Manager->new().

Above comment is misleading: The lines does not initialize a new object (you 
have to instantiate an object yourself, see below); it installs a check that 
the object's attribute is of the Manager class.

> };
>
> $store = Shoppe->new();

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");

# add:

$store->boss(Manager->new);

> $store->boss->name('Prof L. P. Haitch');
> $store->boss->salary('madness');
> $store->boss->started(scalar localtime);
>
>
> print "owner: $store->owner";

This won't print what you want: $store is interpolated, and '->owner' is taken 
literally.

print 'owner: ',$store->owner, "\n";
#or:
#print "owner: @{[ $store->owner ]}\n";


> $someowner =  $store->owner;

my $someowner =  $store->owner;

> print "owner: $owner";
>
> print "addrs: $store->addrs";

The same holds here, plus the method returns an arrayref, not an array

print 'addrs: ', (join ', ', @{$store->addrs}), "\n";

> @some_addrs  = $store->addrs;

my @some_addrs  = join ', ', @{$store->addrs};

> print "addrs: @some_addrs";

my @some_addrs  = join ', ', @{$store->addrs};

# Output:
owner: Abdul Alhazred
owner: Abdul Alhazred
addrs: Miskatonic University, Innsmouth, Mass.
addrs: Miskatonic University, Innsmouth, Mass.


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>


Reply via email to