For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > March 2004 > Passing a struct to a subroutine









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Passing a struct to a subroutine
Graham

2004-03-30, 11:43 am

For some reason I Can't seem to figure this out.

I have a struct:

use Class::Struct;

struct( stuff => {
name => '$',
rank => '$',
serial => '$' }
);


I have an assignment:

$soldier=stuff->new( name=>"Joe");

Now I want to pass this to a subroutine:

PrintSoldierName($soldier);

sub PrintSoldiername {

#
# this doesn't work
#

my $dude=stuff->new;
$dude= @_;
print $dude->name


}



How do I access the passed structure so that I can print the name of
the soldier in PrintSoldierName? I'd list out all the things I have
tried but it would be a very long post. ;-)

Thanks,
Graham
Brian McCauley

2004-03-30, 12:39 pm


graham@dim.com (Graham) writes:

> #
> # this doesn't work
> #
>
> sub PrintSoldiername {
> my $dude=stuff->new;
> $dude= @_;


This sets $dude to the number of arguments passed to PrintSoldiername().

To set $dude to the first argument:

($dude) = @_;

Please remember that in Perl (like Java and unlike C++) we always
handle objects through references (pointers). Setting $dude to point
to the stuff object that was passed to PrintSoldiername() will stop it
pointing to stuff you created on the line above (which will then be
garbage collected).

sub PrintSoldiername {
my ($dude)= @_;
print $dude->name
}

--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com