parse string with pairs of values into hash the Perl6 way

In Perl, there's generally more than one way to do it, and as your problem involves parsing, one solution is, of course, regexes:

my $text = "width=13\nheight=15\nname=Mirek";
$text ~~ / [(\w+) \= (\N+)]+ %% \n+ /;
my %params = $0>>.Str Z=> $1>>.Str;

Another useful tool for data extraction is comb(), which yields the following one-liner:

my %params = $text.comb(/\w+\=\N+/)>>.split("=").flat;

You can also write your original approach that way:

my %params = $text.split("\n")>>.split("=").flat;

or even simpler:

my %params = $text.lines>>.split("=").flat;

In fact, I'd probably go with that one as long as your data format does not become any more complex.


If you have more complex data format, you can use grammar.

grammar Conf {
    rule  TOP   { ^ <pair> + $ }
    rule  pair  {<key> '=' <value>}
    token key   { \w+ }
    token value { \N+ }
    token ws    { \s* }
}

class ConfAct {
    method TOP   ($/) { make (%).push: $/.<pair>».made}
    method pair  ($/) { make $/.<key>.made => $/.<value>.made }
    method key   ($/) { make $/.lc }
    method value ($/) { make $/.trim }
}

my $text = " width=13\n\theight = 15 \n\n nAme=Mirek";
dd Conf.parse($text, actions => ConfAct.new).made;

Tags:

Raku