我是 Perl 新手,我一直在做一些作业。
我有一个文件
abc.txt
。它包含The Bad boy and Good Boy both Went to School
。
我必须编写一个程序来打开文件并仅打印以大写字母开头的单词。
以下是我的程序
my $a = "abc.txt";
open(my $fh,$a) or die "cannot open: $!\n";
while(<$fh>) {
// I need to add the regex here
if ($_ =~ /#REGEX HELP PLEASE/)
# The regex should be generic. The line can change in the file
}
use warnings;
use strict;
my @array = qw(The Bad boy and Good Boy both Went to School);
foreach (@array){
if ($_ =~ /([A-Z][a-z])/){
print "$_\n"
}
}
或者更简单地说:
foreach (@array){
print "$_\n" if /([A-Z][a-z])/;
}
perl -lne 'push @a,/\b([A-Z][a-z0-9]+)\b/g;END{print join "\n",@a}' your_file
测试:
> cat temp
hello world.
This is hello world.
Another hello world.
New hello World.
The Bad boy and Good Boy both Went to School
>
> perl -lne 'push @a,/\b([A-Z][a-z0-9]+)\b/g;END{print join "\n",@a}' temp
This
Another
New
World
The
Bad
Good
Boy
Went
School
>
怎么样:
while(<$fh>) {
my @words = split/\W+/,$_;
foreach (@words) {
print if /^[A-Z]\w+/;
}
}
您需要的正则表达式是
/\b[A-Z]+\S*\b/g
,但您可能还需要稍微更改一下代码。
假设
abc.txt
包含行(字符串)“The Bad boy and Good Boy Both Went to School.”,您可以执行以下操作:
use strict;
use warnings;
my $fileName = 'abc.txt';
open my $fh, '<', $fileName or die $!;
while (<$fh>) {
print $1, "\n" while /([A-Z]\w+)/g;
}
close $fh;
输出:
The
Bad
Good
Boy
Went
School
希望这有帮助!
我认为这会起作用。
my $a = "abc.txt";
open(my $fh,$a) or die "cannot open: $!\n";
while(<$fh>) {
my @b = split(' ',$_);
foreach my $c (@b){
if ($c =~ /([A-Z]\w+)/) {
print "$1\n";
}
}
}
用途:
open(my $fl, 'abc.txt');
while(<$fl>) {
my @array = split(' ', $_);
my @results = grep(/([A,Z]\w+)/, @array);
}
Grep 将返回一个列表,其中包含与表达式匹配的
@array
元素。
您首先必须读取文件的每一行。 然后你必须将每一行分成单词。 确定单词是否以大写字母开头的正则表达式只是
if( /^[A-Z]/ ){ #word starts with upper case letter }
整个程序是这样的
#!/usr/bin/perl -w
while(<>){
my @words = split /\s+/; #split line into words
for(@words){
if(/^[A-Z]/){ #word is upper case
print "$_\n";
}
}
}
输出看起来像这样
$ perl uppercaseWords.pl abc.txt
The
Bad
Good
Boy
Went
School