in reply to Optimizing the use of hashes in subroutines
You also haven't indicated what $val is. In your comment, you say that it generates 4 arrays. If it is a very large scalar, it may be useful to pass the argument as a reference (see References Tutorial & References quick reference) instead of copying the whole thing which is slow.
Additionally, instead of returning the entire hash, you may just want to return a reference to the hash. That would change the my %hash = build_hash($val); to something like my $hash_ref = build_hash($val); You could also not use a return value at all, but build the hash inside the subroutine:
#!/usr/bin/perl -w use strict; my %hash; my $val = "foo bar"; build_hash(\%hash,$val); sub build_hash { my ($hash_ref, $val) = @_; my @vals = split /\s+/ , $val; foreach (@vals) { $hash_ref->{$_} = 1; } }
I am sure there is more optimization that could be done, but this should be a start. The other answers should become obvious after reading the references tutorials I provided.
Cheers - L~R
|
|---|