![](/img/trans.png)
[英]perl: Can't use string as an ARRAY ref while “strict refs” in use
[英]Perl - can't use string (…) as an array ref
我正在用codeeval.com的挑战练习Perl,我遇到了意想不到的错误。 目标是逐行遍历文件,其中每行包含一个字符串和一个用逗号分隔的字符,并在字符串中查找该字符的最右侧出现。 我得到了错误的答案,所以当我收到以下错误时,我更改了代码以打印出变量值:
Can't use string ("Hello world") as an ARRAY ref while "strict refs" in use at char_pos.pl line 20, <FILE> line 1.
我的代码如下。 您可以在标题中看到该文件中的示例。 您还可以看到原始输出代码,该代码错误地仅显示每个字符串中最右侧的字符。
#CodeEval challenge: https://www.codeeval.com/open_challenges/31/
#Call with $> char_pos.pl numbers
##Hello world, d
##Hola mundo, H
##Keyboard, b
##Connecticut, n
#!/usr/bin/perl
use strict;
use warnings;
my $path = $ARGV[0];
open FILE, $path or die $!;
my $len;
while(<FILE>)
{
my @args = split(/,/,$_);
$len = length($args[0]) - 1;
print "$len\n";
for(;$len >= 0; $len--)
{
last if $args[0][$len] == $args[1];
}
#if($len > -1)
#{
# print $len, "\n";
#}else
#{
# print "not found\n";
#}
}
编辑:根据下面的答案,这是我工作的代码:
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
open my $fh,"<",shift;
while(my $line = <$fh>)
{
chomp $line;
my @args = split(/,/,$line);
my $index = rindex($args[0],$args[1]);
print $index>-1 ? "$index\n" : "Not found\n";
}
close $fh;
perl中的字符串是基本类型,而不是可下载数组。 您可以使用substr
函数来获取单个字符(也只是字符串)或来自它们的子字符串。
还要注意字符串比较是用eq
完成的; ==
是数字比较。
看起来您需要了解Perl函数。 Perl有许多用于字符串和标量的功能,并不总是可以直接了解它们。
但是,Perl有一个很棒的函数叫做rindex ,可以完全按你的要求运行。 你给它一个字符串,一个子字符串 (在这种情况下,单个字符),它从字符串的右侧查找该子字符串的第一个位置( 索引从左侧做同样的事情。)
既然您正在学习Perl,那么获得一些有关Modern Perl和标准编码实践的书籍可能是个好主意。 这样,您就会了解更新的编码技术和标准编码实践。
这是一个示例程序:
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
use feature qw(say);
open my $fh, "<", shift;
while ( my $line = <$fh> ) {
chomp $line;
my ($string, $char) = split /,/, $line, 2;
if ( length $char != 1 or not defined $string ) {
say qq(Invalid line "$line".);
next;
}
my $location = rindex $string, $char;
if ( $location != -1 ) {
say qq(The right most "$char" is at position $location in "$string".);
}
else {
say qq(The character "$char" wasn't found in line "$line".)";
}
close $fh;
一些建议:
use autodie
允许程序在open
自动死亡。 无需检查。 open
语句是必要的。 $_
。 chomp
。 最重要的是, 错误检查 ! 我检查行的格式以确保只有一个逗号,并且我正在搜索的字符是一个字符。 我还检查rindex
的退出值,以确保它找到了该字符。 如果rindex
找不到该字符,则返回-1
。
还要知道一行中的第一个字符是0
而不是1
。 您可能需要根据您期望的输出进行调整 。
while($i=<DATA>){
($string,$char)=split(",",$i);
push(@str,$string);}
@join=split("",$_), print "$join[-1]\n",foreach(@str);
__DATA__
Hello world, d
Hola mundo, H
Keyboard, b
Connecticut, n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.