[comp.lang.perl] efficient sets

brendan@cs.widener.edu (Brendan Kehoe) (04/09/91)

 I'm writing a program that uses the table of areacodes; it's in the
form:

	@ac{'ME'} = ( 207 );
	@ac{'PA'} = ( 215, 412, 717, 814 );

 etc etc.
 Is there a more efficient way of doing this? I'm looking for the
fastest way it'll be able to access the tables.

 Thanks for any suggestions.

Brendan
-- 
     Brendan Kehoe - Widener Sun Network Manager - brendan@cs.widener.edu
  Widener University in Chester, PA                A Bloody Sun-Dec War Zone
 Now that we know he has ID, we could give him an account. finger bush@cs....

tchrist@convex.COM (Tom Christiansen) (04/09/91)

From the keyboard of brendan@cs.widener.edu (Brendan Kehoe):
:
: I'm writing a program that uses the table of areacodes; it's in the
:form:
:
:	@ac{'ME'} = ( 207 );
:	@ac{'PA'} = ( 215, 412, 717, 814 );
:
: etc etc.
: Is there a more efficient way of doing this? I'm looking for the
:fastest way it'll be able to access the tables.

First of all, irrespective of this code's efficiency, I seriously question
its correctness.  I don't think what the @ sign is doing here is what
you think it is.

By using an @ sign, you are talking about the elements of the %ac 
array which are ('ME') in the first line and ('PA') in the second.
Normally, you use an @ on an assoc array more like this:

	@ac{'ME','PA'} = ( 207 , '215 412 717 814' );
or perhaps
	@indices = ('ME', 'PA');
	@ac{@indices} = ( 207 , '215 412 717 814' );

otherwise you probably want a simple scalar and not an array assignment:

 	$ac{'ME'} = 207;

Another major problem here is that you can't usefully assign a list to a
scalar.  That's what this here is doing:

	$ac{'PA'} = ( 215, 412, 717, 814 );

If you print out the value of the PAth element of %ac after that 
assigment,  you'll find that it's 814.  That's because in the scalar
context, the comma was taken to be the comma operator, as in C, returning
you the last value in the list.

But you didn't do that; you used an @ and supplied an array context to
the whole thing:

	@ac{'PA'} = ( 215, 412, 717, 814 );

That means that the commas now construct a list, because you're assigning 
a list to a list.  When doing this, extra elements are discarded, so
after this, the PAth element will be 215.  Surprise!

This is a good example of why getting the $ vs @ right is VERY important.

One last thing is that since you can't have lists of lists without 
pulling *references or evals into the picture, I've stored the zips
as a space-delimited list.  You can check whether
	
	$ac{$state} =~ /^b${num}\b/;

If the $num slows you down too much, you might want to go back and
make a list of lists with *references, but this is an exercise best
left up to the reader, cause I'm just too lazy right now. :-)

--tom