How can I extract the values after = in my string with Perl?
10,992
Solution 1
#!/usr/bin/perl
use strict;
use warnings;
# Input string
my $string = "field1=1 field2=2 field3=abc";
# Split string into a list of "key=value" strings
my @pairs = split(/\s+/,$string);
# Convert pair strings into hash
my %hash = map { split(/=/, $_, 2) } @pairs;
# Output hash
printf "%s,%s,%s\n", $hash{field2}, $hash{field1}, $hash{field3}; # => 2,1,abc
# Output hash, alternate method
print join(",", @hash{qw(field2 field1 field3)}), "\n";
Solution 2
use strict;
use warnings;
my $string = 'field1=1 field2=2 field3=abc';
my @values = ($string =~ m/=(\S+)/g);
print join(',', @values), "\n";
Solution 3
$_='field1=1 field2=2 field3=abc';
$,=',';
say /=(\S+)/g
Let's play Perl golf :D
Solution 4
Use m//g
in list context:
#!/usr/bin/perl
use strict;
use warnings;
my $x = "field1=1 field2=2 field3=abc";
if ( my @matches = $x =~ /(?:field[1-3]=(\S+))/g ) {
print join(',', @matches), "\n";
}
__END__
Output:
C:\Temp> klm
1,2,abc
Solution 5
my $str = 'field1=1 field2=2 field3=abc';
print(join(',', map { (split('=', $_))[1] } split(' ', $str)));
Author by
Kristof Mertens
Updated on June 22, 2022Comments
-
Kristof Mertens almost 2 years
I have a string like this
field1=1 field2=2 field3=abc
I want to ouput this as
2,1,abc
Any ideas as to how I can go about this? I can write a small C or Java program to do this, trying I'm trying to find out a simple way to do it in Perl.
-
Michael Carman almost 15 yearsThere's no need to loop. You can grab all the matches at once by using
m//g
in list context. -
Michael Carman almost 15 yearsIf we're playing golf...
perl -E "$_='field1=1 field2=2 field3=abc';$,=',';say /=(\S+)/g"
-
glenn jackman almost 15 years+1 for not resorting to the regex hammer. However: split(/\s+/,$string) is also more simply expressed as split(' ',$string)
-
Lars Haugseth almost 15 yearsTrue, as long as there are single spaces only.