Perl和Foreach循环使用Splitting

dldeef67  于 2023-10-24  发布在  Perl
关注(0)|答案(3)|浏览(131)

我有一个关于Perl的Foreach循环和拆分的问题。
我想循环数组并将其拆分为name和value。
1.)我读取文件并保存为String。
2.)我将空行拆分并保存到Array中。
我的脚本:

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

配置文件:

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

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

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

我的愿望结果:

$name = Testingtttttttttttttttttttttttt
$值= 0987654345678909876 MN 09 uz 6 t56789 oiuhgölkjhgfr 0987654323456789098765 fgnloiuztlkjhgfrtzuiknb
$name = MegaMixoiuzt
$value = 09876543457890098765NSUDlkjhzgtfr67899ztz9098 098765435678987t87656789876567909765
$name =测试部件
$value = 0987654567890098765hzzasza654567uhgdjdjfacdaa 9876545678987654mchfuiaq754567898765434567876

jrcvhitl

jrcvhitl1#

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

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

其他改进:

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

8yoxcaq72#

也像这样没有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
oyjwcjzk

oyjwcjzk3#

您希望按多个#拆分,因此使用#+
+匹配一次或多次。
试试

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

相关问题