[Linux-disciples] Converting an array to a hash

Adam Rosi-Kessel adam at rosi-kessel.org
Wed Oct 6 13:11:36 EDT 2004


On Wed, Oct 06, 2004 at 12:18:23PM -0400, Stephen R Laniel wrote:
> I'd like to read in a file in Perl, then take all the
> English words in that file (as opposed to Perl-regex words)
> and load them into a big hash. The quickest way I can think
> of to do this is something like
> 
> my %wordsHash = ();
> my $infile = join '', <>;
> my @words = ($infile =~ m/([A-Za-z]+)/g);
> foreach my $word (@words) {
> 	$wordsHash{$word} = 1;
> }
> 
> but that's creating an arry (@words) that I don't really
> need. Is there any way to read the words directly into the
> hash?

I doubt you'd be able to measure a performance difference between any of
the various ways of accomplishing this.  Still, if you really want to
skip the array, this should work:

my %wordsHash;
while (<>) {
  foreach my $word (m/([A-Za-z]+)/g) {
    $wordsHash{$word} = defined;
  }
}

I believe there are other ways to read a file directly into a hash, but I
don't remember them off the top of my head.
-- 
Adam Rosi-Kessel
http://adam.rosi-kessel.org
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://lists.bostoncoop.net/pipermail/linux-disciples/attachments/20041006/bebf2366/attachment.pgp


More information about the Linux-disciples mailing list