Mariusz Jucha
Mariusz Jucha

Reputation: 93

Substring, regexp or other way to get specific data from string

I have variable $conf with following content (loaded from file with unix encoded newlines characters):

db_host='127.0.0.1'
db_user='mail_channels'
db_name='mail_channels'
db_pass='kWaNqEvnTCOUnpMI09NljSBXvXCm5DeD'

and I want to get value of db_host, db_user etc. assign to variables $dbHost, $dbUser etc. How can I do this?

Note: I could not read file line by line. The content of $conf variable it's a data I got from request (I have to modify API written in Perl).

Upvotes: 0

Views: 49

Answers (1)

Sobrique
Sobrique

Reputation: 53478

Like this:

 my %conf = $conf =~ m/^(\w+)=\'(.*)\'/gm;

E.g.:

#!/usr/bin/env perl
use strict;
use warnings;

use Data::Dumper;

my $conf = q{ 
    db_host='127.0.0.1'
    db_user='mail_channels'
    db_name='mail_channels'
    db_pass='kWaNqEvnTCOUnpMI09NljSBXvXCm5DeD' 
};

print $conf;

print "\n---\n";

my %conf = $conf =~ m/^(\w+)=\'(.*)\'/gm;
print Dumper \%conf;

This gives you:

$VAR1 = {
          'db_user' => 'mail_channels',
          'db_name' => 'mail_channels',
          'db_host' => '127.0.0.1',
          'db_pass' => 'kWaNqEvnTCOUnpMI09NljSBXvXCm5DeD'
        };

It works because - the g on the regular expression repeats and the m does multiple lines.

With two capture groups we grab paired values (key/value) and when we assign that into the %conf hash, it treats them as key-value pairs.

Breaking down that regex:

my %conf = $conf =~ m/
                        ^                 #start of line anchor
                        (\w+)             #word characters, one more
                         =                #just a literal equals
                         \'(.*)\'         #a quote either side of value
                     /gmx;                #x allows whitespace in the regex

For that second group, it will remove the quotes in your string. If you need to preserve them, you can instead:

my %conf = $conf =~ m/^(\w+)=(.*)/gm;

Upvotes: 3

Related Questions