tags:

views:

386

answers:

3

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!

+18  A: 

With 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).

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.

Chris Lutz
Thank you very much!
Abdel
"perldoc -q string" would have been helpful in this case. The -q option searches in the FAQs and leads to "How can I access or change N characters of a string?" which contains the answer Abdel sought.
+2  A: 

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

#!/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().

Tim
+4  A: 

To remove the last 7 characters:

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

or the somewhat inelegant

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

To get all but the last 7 characters:

substr($str, 0, -7)
ysth