in reply to Error with using structs as subroutine parameters

I guess I have to tell the subroutine to find the definition of the struct elsewhere instead of redefining it

As the parameter you're passing to that function already is an object (blessed reference), there's no need to tell Perl where to find its definition. It already knows...

my $mystruct = new Structname; $mystruct = $ARGV[0];

The second line overwrites the object — thus creating it in the first place seems rather useless.

Also, I guess you meant $_[0] instead of $ARGV[0].

Replies are listed 'Best First'.
Re^2: Error with using structs as subroutine parameters
by dellnak (Initiate) on Jun 08, 2009 at 08:53 UTC

    When I remove use Class::Struct line, I get a following error: Can't call method "value1" without a package or object reference

    I figured the "new" line might be useless, but when nothing else worked I got desperate and figured that can't at least make things worse.

      Here's an example that hopefully clears up the usage:

      use strict; use warnings; use Class::Struct; struct ( 'Structname', { value1 => '$', value2 => '$' } ); sub myfunction { my $mystruct = shift; # alternatively: my $mystruct = $_[0]; return $mystruct->value1." ".$mystruct->value2; } my $mystruct = new Structname; $mystruct->value1('foo'); $mystruct->value2(42); my $value = myfunction($mystruct); print "$value\n"; # "foo 42"

      (This also works if you put the sub in a separate file that you then require.)