[Rd] Perl question

Michael Na Li lina@u.washington.edu
Fri Feb 21 21:21:02 2003


On Fri, 21 Feb 2003, Duncan Murdoch verbalised:

>  I'm working on the installer code, but I don't know Perl well enough.
>  What is a good Perl equivalent of the R statement
>  
>   if ( s %in% c('string1', 'string2', 'string3') )  ...
>  
>  I can do it with 
>  
>   if (s == "string1" || s == "string2" || s == "string3")  ...
>  
>  but I've got a feeling there's a better way to do it using associative
>  arrays.  
>  

Using association arrays,

my @strings = ( 'string1', 'string2', 'string3' );
my %stringhash = ();
@stringhash{@strings} = ( 0..$#strings );
if (exists $stringhash{$s}) ..

I wonder if it might be more efficient using regular expression instead,

if ($s =~ /^string[1-3]$/) { ...

it will depends on how 'regular' the strings are, of course.

Michael