Parsing a string with value pairs in a Perl6 hash

I have a line that looks like this:

width=13 height=15 name=Mirek 

I want to turn it into a hash (using Perl 6). Now I do it like this:

 my $text = "width=13\nheight=15\nname=Mirek"; my @lines = split("\n", $text); my %params; for @lines { (my $k, my $v) = split('=', $_); %params{$k} = $v; } say %params.perl; 

But I feel that there needs to be a more concise, more idiomatic way to do this. Whether there is a?

+5
source share
2 answers

In Perl, there is usually more than one way to do this, and since your problem involves parsing, one solution, of course, has a regex:

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

Another useful tool for extracting data is comb() , which produces the following single-line file:

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

You can also write your original approach this way:

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

or even simpler:

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

In fact, I would probably go with this until your data format becomes more complex.

+8
source

If you have a 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; 
+1
source

Source: https://habr.com/ru/post/1212876/