Developer Developer - 2 months ago 9
Perl Question

Get all values in a hash from string after equals sign Perl

I have a string like this

"Test string has tes value like abc="123",bcd="345",or it it can be xyz="4567" and ytr="434""
.

Now what i want to get the values after equals sign.The hash structure while be like this :

$hash->{abc} =123,
$hash->{bcd} =345,
$hash->{xyz} =4567,


i have tried this
$str =~ / (\S+) \s* = \s* (\S+) /xg

Answer

The regex returns the captured pairs, which can be assigned to a hash, made anonymous.

use warnings 'all';
use strict;
use feature 'say';

my $str = 'Test string has tes value like abc="123",bcd="345",or it '
        . 'it can be xyz="4567" and ytr="434"';    

my $rh = { $str =~ /(\w+)="(\d+)"/g }

say "$_ => $rh->{$_}" for keys %$rh ;

Prints

bcd => 345
abc => 123
ytr => 434
xyz => 4567

Per comment: for possible spaces around the equality sign, change it to \s*=\s*.