我在'input.txt'文件中有以下详细信息。
/u02/users/student1/marks score: 97 subject: sub1 status: passed
/u02/users/student2/marks score: 20 subject: sub1 status: failed
/u02/users/student3/marks score: 80 subject: sub1 status: passed
/u02/users/student4/marks score: 60 subject: sub1 status: passed
/u02/users/student5/marks score: 50 subject: sub1 status: passed
/u02/users/student6/marks score: 45 subject: sub1 status: failed
/u02/users/student7/marks score: 99 subject: sub1 status: passed
我正在尝试拆分字符串并打印特定字段。 输出我正在寻找: student1标记得分:97 student2标记得分:20 student3标记得分:80 student4标记得分:60 student5分数得分:50 student6标记得分:45 student7标记得分:99
这是我写的代码。但看起来有一些问题,并低于错误。请纠正我。
在script.pl第6行的语法错误,靠近“) 打印” 由于编译错误,script.pl的执行中止。
#!/usr/bin/perl
use strict;
use warnings;
while (defined (my $line = <>)) {
my @lines = split(/\//, $line)
print "$lines[3] $lines[4] $lines[5] $lines[6]\n";
}
答案 0 :(得分:1)
您的split命令在/
分割,产生5个字段,第一个字段始终为空。您想要的字段是3和4.要获得所需的输出,您需要在得分后删除主题,您可以使用s//
运算符:
my $student = $lines[3];
my $score = $lines[4];
$score =~ s/ subject:.*$//;
print "$student $score\n";
答案 1 :(得分:1)
在这种情况下,我使用从源代码构建的正则表达式。
你有这条线:
/u02/users/student1/marks score: 97 subject: sub1 status: passed
从这一行开始,你真的需要学生和它的分数,所以你正在建立正则表达式:
/u02/users/(.+?)/(marks score: \d+) subject:
代码将是:
use v5.10;
while (my $line = <>) {
if( $line =~ m{/u02/users/(.+?)/(marks score: \d+) subject} ){
say "$1 $2";
}
}
答案 2 :(得分:0)
你错过了分号和分裂的结束。这就是语法错误的原因
#!/usr/bin/perl
use strict;
use warnings;
while (defined (my $line = <>)) {
my @lines = split(/\//, $line);
my ($scr) = $lines[4] =~m/(.+?)subject/;
print " $lines[3] $scr \n";
}
答案 3 :(得分:0)
目前还不清楚您想要实现的目标,但语法错误是因为my @lines = split(/\//, $line)
之后您缺少分号
您还会发现,split
并未按预期划分每一行。例如,第一行输入产生了这个
@lines = (
" ",
"u02",
"users",
"student1",
"marks score: 97 subject: sub1 status: passed\n",
)
你不能说出你希望得到什么结果,但猜测你只想要不同的信息:学生,分数,主题和状态
您可以这样写,将数据分成 斜线或空格
use strict;
use warnings 'all';
while ( <DATA> ) {
my @lines = split qr{/|\s};
shift @lines until $lines[0] =~ /\S/;
print "$lines[2] $lines[5] $lines[7] $lines[9]\n";
}
__DATA__
/u02/users/student1/marks score: 97 subject: sub1 status: passed
/u02/users/student2/marks score: 20 subject: sub1 status: failed
/u02/users/student3/marks score: 80 subject: sub1 status: passed
/u02/users/student4/marks score: 60 subject: sub1 status: passed
/u02/users/student5/marks score: 50 subject: sub1 status: passed
/u02/users/student6/marks score: 45 subject: sub1 status: failed
/u02/users/student7/marks score: 99 subject: sub1 status: passed
student1 97 sub1 passed
student2 20 sub1 failed
student3 80 sub1 passed
student4 60 sub1 passed
student5 50 sub1 passed
student6 45 sub1 failed
student7 99 sub1 passed