Skydreampower
Skydreampower

Reputation: 43

Perl and Foreach loop with Splitting

I have a Problem about the Foreach Loop and Splitting with Perl.

I want to loop the Arrays and split it to name and value.

1.) I read the File and save to an String.

2.) I split the empty line and save to an Array.

My Script:

#!/usr/bin/perl

use strict;

my $pathconfigfile = 'config.conf';
my @configline;

open(my $configfile, "<", $pathconfigfile);

local $/;
my @configdata  = split("\n\n",<$configfile>);

#print $configdata[0], "\n";
#print $configdata[1], "\n";
#print $configdata[2], "\n";

foreach my $data (@configdata){
        my @editing = split /#/, $data;
        my ($name, $value) = @editing[0,1];
        print $name "\n";
        print $value "\n";
}

close $configfile;

Configfile:

Testingtttttttttttttttttttttttt
############################################
0987654345678909876MN09uz6t56789oiuhgölkjhgfr
0987654323456789098765fgnloiuztlkjhgfrtzuiknb

MegaMixoiuzt
############################################
09876543457890098765NSUDlkjhzgtfr67899ztz9098
098765435678987t87656789876567898765679097658

TESTINGPARTS
############################################
0987654567890098765hzzasza654567uhgdjdjfacdaa
9876545678987654mchfuiaq754567898765434567876

My wish result:

$name = Testingtttttttttttttttttttttttt

$value = 0987654345678909876MN09uz6t56789oiuhgölkjhgfr 0987654323456789098765fgnloiuztlkjhgfrtzuiknb

$name = MegaMixoiuzt

$value = 09876543457890098765NSUDlkjhzgtfr67899ztz9098 098765435678987t8765678987656789876567909765

$name = TESTINGPARTS

$value = 0987654567890098765hzzasza654567uhgdjdjfacdaa 9876545678987654mchfuiaq754567898765434567876

Upvotes: 0

Views: 6266

Answers (3)

mkHun
mkHun

Reputation: 5927

You want to split by multiple # so use #+

+ match one or more times.

Try it

#!/usr/bin/perl

use strict;

my $pathconfigfile = 'config.conf';
my @configline;

open(my $configfile, "<", $pathconfigfile);

local $/;
my @configdata  = split("\n\n",<$configfile>);


foreach my $data (@configdata){
    my ($name,$value) = split /\n#+\n/, $data;
    print "$name $value\n\n";
}

Upvotes: 1

ikegami
ikegami

Reputation: 385565

 split /#/          # A "#" separates the two.

should be

 split /\n#+\n/     # A line of "#" separates the two.

With other improvements:

#!/usr/bin/perl

use strict;
use warnings;

my $config_qfn = 'config.conf';

open(my $config_fh, "<", $config_qfn )
    or die("Can't open \"$config_qfn\": $!\n");

local $/ = "";  # Paragraph mode
while (my $rec = <$config_fh>) {
    my ($name, $value) = split(/\n#+\n/, $rec);
    print "\$name = $name\n";
    print "\$value = $value\n";
}

Upvotes: 3

red0ct
red0ct

Reputation: 5055

Also something like this without foreach:

use strict;
use warnings;

open my $fh, '<config.conf' or die "$!"; my $data = join '', <$fh>; close $fh;
my %hash = $data =~ /^(.+)\n#+\n(\S+\n\S+)/mg;
print "NAME: $_\nVALUE: $hash{$_}\n\n" for keys %hash

Upvotes: 2

Related Questions