string 如何删除 Perl 中哈希值的最后七个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/846257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:26:14  来源:igfitidea点击:

How can I remove the last seven characters of a hash value in Perl?

perlstring

提问by Abdel

I need to cut off the last seven characters of a string (a string that is stored in a hash). What is the easiest way to do that in perl? Many thanks in advance!

我需要剪掉一个字符串(存储在哈希中的字符串)的最后七个字符。在 perl 中最简单的方法是什么?提前谢谢了!

回答by Chris Lutz

With substr():

substr()

substr($string, 0, -7);

I suggest you read the Perldoc page on substr()(which I linked to above) before just copying and pasting this into your code. It does what you asked, but substr()is a very useful and versatile function, and I suggest you understand everything you can use it for (by reading the documentation).

我建议您先阅读 Perldoc 页面substr()(我在上面链接到),然后再将其复制并粘贴到您的代码中。它可以满足您的要求,但它substr()是一个非常有用且用途广泛的功能,我建议您了解可以使用它的所有内容(通过阅读文档)。

Also, in the future, please consider Googling your question (or, in the case of Perl, looking it up on Perldoc) before asking it here. You can find great resources on things like this without having to ask questions here. Not to put down your question, but it's pretty simple, and I think if you tried, you could find the answer on your own.

此外,将来,请考虑在此处提出问题之前使用谷歌搜索您的问题(或者,在 Perl 的情况下,在 Perldoc 上查找)。您无需在此处提问即可找到有关此类内容的大量资源。不是放下你的问题,但它很简单,我想如果你尝试过,你可以自己找到答案。

回答by ysth

To remove the last 7 characters:

删除最后 7 个字符:

substr($str, -7) = '';

or the somewhat inelegant

或者有些不雅的

substr($str, -7, length($str), '');

To get all but the last 7 characters:

要获取除最后 7 个字符之外的所有字符:

substr($str, 0, -7)

回答by Tim

Use the perl substrfunction, but make the "length" argument negative. Example:

使用 perlsubstr函数,但将“长度”参数设为负数。例子:

#!/usr/bin/perl

my $string = "string";
$short = substr($string, 0, -3);
printf $short . "\n";

This will return the string "str" with a newline, since we specified truncating the last three characters. Take a look at the Perl documentation on substr().

这将返回带有换行符的字符串“str”,因为我们指定截断最后三个字符。查看关于 substr()Perl 文档