in reply to Re: extracting the key value pairs from a string
in thread extracting the key value pairs from a string

This is brilliant.... but what exactly is going on here?
  • Comment on Re^2: extracting the key value pairs from a string

Replies are listed 'Best First'.
Re^3: extracting the key value pairs from a string
by Athanasius (Archbishop) on Dec 30, 2017 at 08:04 UTC

    Hello alphacoorg, and welcome to the Monastery!

    $s=~/([^ :]+)/g

    The square brackets create a bracketed character class and the initial ^ (caret) negates what follows, so this character class matches any character other than a space or a colon. The + quantifier means one or more, and the surrounding parentheses create a capture group. Finally, the /g modifier creates a global match, and since the expression is evaluated in list context, the global match returns a list of matches.

    That is, the regular expression returns a list of the substrings in '   ABC: 123 xyz: 100    def: YYY    aaa: ZZZ' that do not contain space or colon characters:

    ("ABC", 123, "xyz", 100, "def", "YYY", "aaa", "ZZZ")

    (You can verify this yourself by assigning the output of the regular expression to an array instead of a hash, and then printing out the array.)

    In Perl, assigning a list to a hash populates the hash with key/value pairs taken in sequence from the list. So in this case, the hash is created with entries:

    "ABC" => 123, "xyz" => 100, etc.

    (Note that Perl’s “fat comma” =>, which is what you normally use when assigning key/value pairs to a hash, is really just an ordinary comma, functioning as a list separator, with the additional property that the expression on its left-hand side is turned into a string.)

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,