Pete Emerson wrote:
> Is there an elegant way to make sure that a string contains a list of
> strings, but not necessarily in any particular order? Here's how I'm
> doing
> it:
>
> #!/usr/bin/perl -w
>
> use strict;
> my @strings=qw(onetwothree threeonetwo onetwonope);
> my @matches=qw(one two three);
> foreach my $string (@strings) {
>     my $success=1;
>     foreach my $match (@matches) {
>         ($string=~/$match/) ? (next) : ($success=0);

You're using the conditional expression for its side-effects
here, which is frowned upon. Also your match may not do
what you want if it contains any regex metacharacters like
'.'.

>         last;

'last' won't do anything here, as it's on the last line of the loop
anyway. It needs to be within the conditional block to be useful.

>     }
>     ($success) ? (print "$string matches.\n") : (print "$string does
> not match.\n"); }

Conditional expression for its side-effects again!

I would use 'grep', except that there's no way of stopping it
checking the entire list if it finds a mismatch part-way through.

How about this, which also avoids the problem of two match
strings sharing a character in the object string, as in
'twonethree', the last on the list. The last line shows the
conditional expression in use with just passive expressions
as its operands.

HTH,

Rob


    #perl
    use strict;
    use warnings;

    my @strings=qw( onetwothree threeonetwo onetwonope twonethree );
    my @matches=qw( one two three );

    foreach (@strings) {

        my $string = $_;
        my $ok;

        foreach my $match (@matches) {
            last unless ($ok = s/\Q$match//);
        }

        printf "%s %s\n", $string, $ok ? 'matches' : 'doesn\'t match';
    }
    __END__



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to