Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i have an element of an array which looks something like this;
/:swiss|Q9L572|DNAA_STRPY /:tremblnew|AAK98805|AAK98805 /:swiss|O08397|DNAA_STRPN
etc in a long list. i am trying to write a script that extracts all hits beggining with /:swiss. My attempted if statement is below, it doesn't get any error messages but it also doesn't run! can anyone help??
if ($array[1] eq /^\/:swiss| (\d+)|(\d+)/) { print $array[1]; }

Replies are listed 'Best First'.
Re: selecting within elements of arrays
by broquaint (Abbot) on Jun 05, 2002 at 10:30 UTC
    The problem is that you're not escaping the meta-character pipe(|) which alternates sequences in regex (see. perlre for more info on regexes). Also you're using the string comparision operator and not the regex matching operator =~ (see. perlop for more info on operators in perl) to match on $array[1]. To get your example to work you could do something like this
    if($array[1] =~ m{ /:swiss \| \w+ \| \w+ }x) { ... }
    And if you wanted to do this match on an array of strings you could do something like this
    my $match_re = qr{ ^ /:swiss \| \w+ \| \w+ }x; foreach my $line (@array_of_strings) { if($line =~ /$match_re/) { ... } }

    HTH

    _________
    broquaint

Re: selecting within elements of arrays
by Joost (Canon) on Jun 05, 2002 at 10:35 UTC
    Your match doesn't work because you have whitespace in your regex, and you don't use the /x modifier, and you don't escape the '|' - oh and you cannot match a regex with 'eq' - you need '=~' (or match the $_ var) .

    You might also try simplifying the match:

    foreach (@array) { # means foreach $_ (@array) { next unless /^\/:swiss\|/; # means next unless $_ =~ /^\/:swiss\|/; print; # means print $_; }
    -- Joost downtime n. The period during which a system is error-free and immune from user input.