tom smith wrote:
On Fri, Nov 6, 2009 at 12:15 AM, John W. Krahn <jwkr...@shaw.ca> wrote:

Michael Alipio wrote:

 if I have a script that accepts any combination of the 5 or maybe even
more options, say, option1, option2, option3...

Now, after collecting the options, for each option, there is a
corresponding regexp pattern. I will then build an if statement, where
the test should be, all the options entered must match (&&) otherwise,
return false.
I'm thinking this can only be done by nested if's:

if ($word =~ /$option1/ && $word =~ /$option2){
 if ($word =~ /$option3/ && $word =~ /$option4){
    if ($word =~ /$optionN/){
       print "All pattern matched!\n";
    }
 }
}

Now I'm thinking, it is quite impossible to dynamically create all
those if tests. Perhaps I can just open a file for writing, write a
new perl script which will have those codes, and execute it at the end.
Is there a better way of doing this?

You could use the Getopt::Long module to get multiple options into an
array:

perldoc Getopt::Long
[ snip ]

Then to test them all:

if ( @options = grep $word =~ /$_/, @options ) {

   print "All pattern matched!\n";
   }

I don't understand how that grep works.  Here is an example I constructed:

my $word = 'ac';
my @options = ('a', 'b', 'c');

@options = grep $word =~ /$_/, @options;

print "@options\n";

if (@options) {print "They all matched!\n"}

The way I understand it, if @options isn't an empty array then the if
condition will evaluate to true.  It appears to me that @options will not be
empty if only one pattern matches the word.

Sorry, I made an error in that previous posting, it should be:

if ( @options == grep $word =~ /$_/, @options ) {
    print "All pattern matched!\n";
    }


For example:

$ perl -le'
my $word = "ac";
my @options = qw( a b c );
if ( @options == grep $word =~ /$_/, @options ) {
    print "All pattern matched!\n";
    }
'

$ perl -le'
my $word = "acb";
my @options = qw( a b c );
if ( @options == grep $word =~ /$_/, @options ) {
    print "All pattern matched!\n";
    }
'
All pattern matched!




John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to