Using the answer above, here are some "quick" (to the programmer) ways to initalize a set:
Using a hash slice
foreach (@fruit{'apple','banana','plum'}){$_=1}
This method works best when your set will not change, because you (pretty much) have to hardcode this string in.
That is:
#This will NOT work as intended
$value="'apple','banana','plum'";
foreach (@fruit{$value}){$_=1}
#doesn't work!
Often you will not know the set you want at write-time, so you will want to be able to push and pop the set from an array. Converting an array into a set can be done like:
@array=("apple","banana");
push @array, "plum";
foreach (@array){$fruit{$_}=1}
These foreach loops can obfuscate your code, so a simple
foreach (@array){$fruit{$_}=1} # initialize fruit set
can greatly increase readability of code while not complicating your programming efforts
|