⭐ in reply to How do I use a hash as a set?
Using a hash slice
This method works best when your set will not change, because you (pretty much) have to hardcode this string in.foreach (@fruit{'apple','banana','plum'}){$_=1}
#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:
These foreach loops can obfuscate your code, so a simple@array=("apple","banana"); push @array, "plum"; foreach (@array){$fruit{$_}=1}
can greatly increase readability of code while not complicating your programming effortsforeach (@array){$fruit{$_}=1} # initialize fruit set
|
|---|