我有一个提供两个参数的方法:一个数组和一个字符串。问题是,当我初始化两个不同的变量时,一个用于数组,一个用于字符串,我在第一个变量中得到数组的第一个元素,在第二个变量中得到第二个元素。我的问题是如何将整个数组存储在一个变量中,将字符串存储在另一个变量中?
Analyze.pm
sub analyze {
my $self = shift;
my ($content, $stringToSearch) = @_;
# my ($stringToSearch) = @_;
print "$stringToSearch";
if (!defined($stringToSearch) or length($stringToSearch) == 0) { die 'stringToSearch is not defined yet! ' }
foreach my $element ($content) {
#print "$element";
my $loc = index($element, $stringToSearch);
# print "$loc\n";
given ($stringToSearch) {
when ($stringToSearch eq "Hi") {
if ($loc != 0) {
print "Searched word is Hi \n";
} else {
print "No word found like this one! "
}
}
#when ($stringToSearch == 'ORIENTED_EDGE') {
# print 'Searched word is ORIENTED_EDGE';
#} # Printed out because i dont need it now!
}
break; # For testing
}
}
example.pm
my @fileContent = ('Hi', 'There', 'Its', 'Me')
my $analyzer = Analyze->new();
$analyzer->analyze(@fileContent, 'Hi');
当我更改$content
为@content
它时,将数组和字符串的所有值放入@content
我希望有人能够帮助我。我是Perl的初学者。提前致谢
您不能将数组传递给子(或方法),而只能传递标量列表。因此,
$analyzer->analyze(@lines, 'Hi');
与...相同
$analyzer->analyze($lines[0], $lines[1], ..., 'Hi');
这意味着以下内容将无法正常工作:
my (@strings, $target) = @_;
Perl不知道原始数组中有多少个项目,因此将它们全部放入中@strings
,而$target
未定义。
解决方案
您可以执行以下操作:
sub analyze {
my $self = shift;
my $target = pop;
my @strings = @_
for my $string (@strings) {
...
}
}
$analyzer->analyze(@lines, 'Hi')
还是没有不必要的副本:
sub analyze {
my $self = shift;
my $target = pop;
for my $string (@_) {
...
}
}
$analyzer->analyze(@lines, 'Hi')
先通过目标会更容易。
sub analyze {
my ($self, $target, @strings) = @_;
for my $string (@strings) {
...
}
}
$analyzer->analyze('Hi', @lines)
还是没有不必要的副本:
sub analyze {
my $self = shift;
my $target = shift;
for my $string (@_) {
...
}
}
$analyzer->analyze('Hi', @lines)
您还可以将引用传递给数组(以您喜欢的任何顺序),因为引用是标量。
sub analyze {
my ($self, $target, $strings) = @_;
for my $string (@$strings) {
...
}
}
$analyzer->analyze('Hi', \@lines)
我会倒数第二。它遵循与众所周知的相同的一般模式grep
。
my @matches = grep { condition($_) } @strings;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句