JamesNC has asked for the wisdom of the Perl Monks concerning the following question:

Hi all... I have tried to run this example from Class::Struct , I cannot use this syntax with similar examples in the Perl Black Book either. (Win32, Perl 5.8) could someone explain what is going on? (The other two examples in the pod work but use a different syntax )
use Class::Struct; #use strict; struct( rusage => { ru_utime => timeval, # seconds ru_stime => timeval, # microseconds }); struct( timeval => [ tv_secs => '$', tv_usecs => '$', ]); # create an object: my $t = new rusage; # $t->ru_utime and $t->ru_stime are objects of type timeval. # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec. $t->ru_utime->tv_secs(100); $t->ru_utime->tv_usecs(0); $t->ru_stime->tv_secs(5); $t->ru_stime->tv_usecs(0);

Error:
Can't call method "tv_secs" on an undefined value at C:\cgi-bin\struct.pl line 26.

This is mostly a curiousity question as I haven't really needed to use these and do the same thing with HoH, etc. But I wanted to learn something new. Thanks, James.

Replies are listed 'Best First'.
Re: Class::Struct example fails..syntax problem?
by bbfu (Curate) on Apr 18, 2003 at 21:30 UTC

    From the Class::Struct docs (emphasis added):

        Class ('Class_Name' or '*Class_Name')
            The element's value must be a reference blessed to the named class
            or to one of its subclasses. The element is not initialized by
            default.
    
            The accessor's argument, if any, is assigned to the element. The
            accessor will "croak" if this is not an appropriate object
            reference.
    

    So, basically, your ru_utime and ru_stime elements are not yet initialized. You must do so yourself, like so:

    #!/usr/bin/perl use Data::Dumper; use Class::Struct; use strict; struct( rusage => { ru_utime => 'timeval', # seconds ru_stime => 'timeval', # microseconds }); struct( timeval => [ tv_secs => '$', tv_usecs => '$', ]); # create an object: my $t = new rusage; # Initialize ru_utime and ru_stime $t->ru_utime(new timeval); $t->ru_stime(new timeval); # $t->ru_utime and $t->ru_stime are objects of type timeval. # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec. $t->ru_utime->tv_secs(100); $t->ru_utime->tv_usecs(0); $t->ru_stime->tv_secs(5); $t->ru_stime->tv_usecs(0); print Dumper($t),"\n";

    Also, you must put quotes around 'timeval' so that it will pass strict.

    bbfu
    Black flowers blossom
    Fearless on my breath

      ah ha.. thank you very much bbfu :)