For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > August 2005 > Running 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 Running a subroutine
Octavian Rasnita

2005-08-02, 5:00 pm

Hi,

If I want to run a subroutine passing some parameters, which is the best way
to do it if that subroutine won't modify those parameters but just use them?

1.
&subroutine(%hash);
sub subroutine {
%hash = @_;
}

2.
&subroutine(\%hash);
sub subroutine {
$ref = shift;
$hash = %$ref;
}

3.
&subroutine(%hash);
sub subroutine {
$ref = { @_ };
}

4.
&subroutine({ %hash });
sub subroutine {
$ref = shift;
}

The most important thing is the speed and using as less memory as possible.

Thank you.

Teddy


Jeff 'japhy' Pinyan

2005-08-02, 5:00 pm

On Aug 2, Octavian Rasnita said:

> If I want to run a subroutine passing some parameters, which is the best way
> to do it if that subroutine won't modify those parameters but just use them?


There's always the *potential* to modify the things you send a function,
but only if you're really specific about what you do.

Suffice to say, it's wiser to pass a reference to an array or hash than
pass the array or hash, especially if it's large. I would pass a
reference to the hash and use the reference (not dereference it). YOU
should make sure YOU don't change the hash.

> The most important thing is the speed and using as less memory as possible.


Then it's certainly

do_this(\%hash);

sub do_this {
my $href = $_[0];
print $href->{key}; # etc.
}

Pass a reference, and don't dereference it!

--
Jeff "japhy" Pinyan % How can we ever be the sold short or
RPI Acacia Brother #734 % the cheated, we who for every service
http://japhy.perlmonk.org/ % have long ago been overpaid?
http://www.perlmonks.org/ % -- Meister Eckhart
Sponsored Links







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

Copyright 2008 codecomments.com