in reply to Regex to array

If you trust that your data will be well-formed, you can simply match what you want to keep instead of splitting the string:

my %values = ($string =~ /(SECTION \d+)\s+(.*?)/sg);

That idea doesn't work :-/ :

my $string = <<STR; SECTION 1 This is section 1 SECTION 2 This is section 2 STR use Data::Dumper; my %values = ($string =~ /(SECTION \d+)\s+(.*?)/sg); print Dumper \%values;

Replies are listed 'Best First'.
Re^2: Regex to array
by Eily (Monsignor) on Jan 09, 2018 at 13:40 UTC

    It works if you add an end marker for the right part:

    use Data::Dump qw( pp ); my $str = <<_BLA_; SECTION 1 bla bla bla SECTION 2 blabla blabla SECTION 3 bla _BLA_ my %hash = $str =~ /(SECTION \d+)\s*(.*?)(?=SECTION|$)/sg; pp \%hash; __DATA__ { "SECTION 1" => "bla bla\nbla\n", "SECTION 2" => "blabla\nblabla\n", "SECTION 3" => "bla", }
    Edit: \s* rather than \s+ to allow empty section at EOF

      Greetings Eily

      Your solution was the only which made the job correctly done - thanks. Still, thanks to all too.

      Kind regards,

      Kepler