How can I extract the values after = in my string with Perl?

extract, perl, string

Solution

#!/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";

Problem

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.

Original source