Perl performance question

Status
Not open for further replies.

petrov

Ars Tribunus Militum
2,714
is this:
code:<HR>
Code:
my @ary = @{ &getfile($file) };

substantially faster than this:
code:<HR>
Code:
my @ary = &getfile2($file);

where getfile looks like:
code:<HR>
Code:
sub getfile
{
    my $file = shift;
    open(FILE, $file) or die;
    my @lines = <FILE>
    close(FILE) or die;
    return @lines;  # or return \@lines
}

for very large files (but not bigger than main memory).

thanks,
--sam
 

sittidae

Ars Centurion
325
Subscriptor
If you want to use your sub getfile then I would have it return an array reference (like you have commented out). In perl, arrays that are passed (and returned) from subroutines get converted into a list. Then the recieving array will be populated with that list. So what you need to do is something like the following:
code:<HR>
Code:
my $ary_ref = &getfile($file);<P>sub getfile
{
......
return \@lines;
}

You can access the entire array by @{$ary_ref}. See the perl man pages for more information.
 

petrov

Ars Tribunus Militum
2,714
jem, the reason is because a reference, aka returning \@lines is the same as returning a pointer, rather than invoking the copy. But I'm not sure if the deference of that pointer causes the array copy to occur anyways, i.e. does @foo = @{ $ref } invoke a full copy.

low level optimizing of perl is sort of counter productive but it was more just a case of curiosity than anything seriously critical.

--sam
 
Status
Not open for further replies.