Matching multiple strings from a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gwigg
    New Member
    • Feb 2008
    • 4

    Matching multiple strings from a file

    Hi, I am trying to match multiple strings per line from a file and extract them into an array. Apparently the first match is assigned $1, how do I know what the last match is ie $last?? I would like to set up a for loop to enter these values into an array: psuedo code below to extract all html tag per line in the file master, array is mastertags:

    while (<$master>)
    {
    $_=~/(<.*?>)/g;
    for (my $i=1; $i <= last value; $i++)
    {
    $mastertags [$x]=$i;
    $x++;
    }
    }
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    The value of $1 changes dynamically with each match found. In your case, though you are using /g option, you are not using a loop to parse through each match and end up getting only the first match in each line. You can try this:
    Code:
    my $m;
    while(<>) {
      push @mastertags,$1 while(/(<.*?>)/g) ; ## push all the matches into array
      $m=$1;      ## holds the string matched
    }
    print "last string matched:$m\n\n";  
    print "$_\n" foreach(@mastertags);

    Comment

    Working...