1

Is there a way of removing the very last character from an array?

Just to be clear, I am not asking for every entry in the array to have its last character removed, only the very last entry into the array should have its last character deleted.

I have looked at chop/chomp/push/pop etc but alot is related to removing values from strings.

4

2 回答 2

9

chop是正确的工具,但它需要一个参数列表。如果你传递一个数组,所有元素都会被切碎。相反,只需使用 index -1。这总是给你最后一个元素。

my @foo = qw(foo bar baz);
chop $foo[-1];
print Dumper \@foo;

# ['foo', 'bar', 'ba']

文档

如果你切分一个列表,每个元素都会被切分。仅返回最后一个印章的值。

于 2013-05-03T13:17:17.723 回答
2

popand命令添加或删除数组上的push整个最后一个条目。这些(和他们的伙伴,unshiftshift)不会作用于单个角色。

chomp命令仅删除\n. 它是在 Perl 4.0 中添加的,用于替换命令,作为从文件中读取一行时chop删除字符的标准方法。\n这是因为chomp如果最后一个字符不是\n. 这意味着即使您不确定它的末尾chomp是否有 a,您也可以安全地使用字符串。\n

chop命令完全符合您的要求。它会删除最后一个字符,无论该字符是什么。在早期版本的 Perl 中,您应该检查chop返回的内容以确保它是一个\n字符。这就是你想要的。

您遇到的问题是两者都chompchop不仅在标量上下文上运行,而且在数组和哈希上下文上也运行。在散列和数组上下文中,它们作用于所有标量数据(但不是散列中的键)。毕竟,如果我读入整个文件,这几乎就是我想要的:

my @file_data = <$file_fh>;  #Reads in the entire file into an array
chomp @file_data;            #Removes all `\n` in one fell swoop

所以,当你这样做时:

chop @my_array;

它正在做 Perl 认为你想要的,而不是你真正想要的——只删除数组最后一个条目中的最后一个字符。

您要做的只是指定该数组中的最后一个条目,然后将其剔除。有两种方法可以做到这一点:

$my_array[ $#my_array ];
$my_array[ -1 ];

$#my_array第一个使用等于数组中最后一个条目的索引的事实。第二个采用 Perl 快捷方式,其中负条目反映数组的末尾:

$my_array[-1];  #Last entry of the array
$my_array[-2];  #Second to the last entry

您将在 Perl 脚本中看到这两种方式。现在,您可以chop仅在数组的最后一个条目上使用:

chop $my_array[-1];
chop $my_array[ $#my_array ];
于 2013-05-03T14:40:04.013 回答