Using regular expressions, use a technique that I like to call like-and-stretch: binding to functions that you know will be there (sticky), and then grab what's in between (stretching).
In this case, you know that one assignment corresponds to
\b\w+=.+
and many of them are repeated in $string . Remember that \b means the word boundary:
A word boundary ( \b ) is a spot between two characters that has a \w on one side of it and a \w on the other side (in any order), counting the imaginary characters as the beginning and end of the line in accordance with \w .
The values ββin the assignments can be a little complicated to describe with a regular expression, but you also know that each value will end with a space, but not necessarily the first space encountered! - after another assignment or ending -string.
To avoid repeating the statement template, compile it once with qr// and reuse it in your template along with look-ahead assertion (?=...) to stretch the match far enough to fix the whole value, and also not let it flow into the next variable name.
Matching your pattern in a list context with m//g gives the following behavior:
The /g modifier defines global pattern matching, that is, matching as much as possible per line. How he behaves depends on the context. In the context of the list, it returns a list of substrings matching any parentheses in the regular expression. If there are no parentheses, it returns a list of all matching lines, as if there were parentheses around the entire pattern.
$assignment uses non-greedy .+? to disable the value as soon as the viewing window sees a different destination or end of line. Remember that a match returns substrings from all captured subpatterns, so alternate rotation uses non-capturing (?:...) . qr// , by contrast, contains implicit parentheses for parentheses.
#! /usr/bin/perl use warnings; use strict; my $string = <<'EOF'; var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello EOF my $assignment = qr/\b\w+ = .+?/x; my @array = $string =~ /$assignment (?= \s+ (?: $ | $assignment))/gx; for ( my $i = 0; $i < scalar( @array ); $i++ ) { print $i.": ".$array[$i]."\n"; }
Output:
0: var1 = 100
1: var2 = 90
2: var5 = hello
3: var3 = "a, b, c"
4: var7 = test
5: var3 = hello