[Simple] Function arguments and return value

G

Gao Chao

I don't know how to write a function with arguments and return values
that are not scalars. I have learn to write something like

sub foo {
my $arg1 = shift;
my $arg2 = shift;

return $bar;
}

but I cannot pass lists or file handles like that. Can somebody
explain me how to pass lists and file handles as arguments and return
values of a function?

Thanks!

GC
 
A

Amir Kadic

Gao said:
but I cannot pass lists or file handles like that. Can somebody
explain me how to pass lists and file handles as arguments and return
values of a function?

You can pass (and return) lists by reference:

sub foo {
my $arrayref= shift;

print $$arrayref[0];
return $arrayref;
}


If you don't want to write $$arrayref all the time, you
can create local aliases, like this:

sub foo {
local (*array1,*array2,...) = @_; # can't use 'my' here

print @array1[0];
}

but you still have to pass array _references_ to the sub.

Filehandles can be 'passed' by passing typeglobs:

sub write {
local *GLOB= shift;
my @otherparameters= @_;

print GLOB @otherparameters;
}

write *STDIN,1,2,3;

You can also use references to typeglobs, the IO:File module, etc...


HTH
Amir
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top