Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I remove the last 20 bytes from a string?

Status
Not open for further replies.

Newbee21369

Programmer
Oct 13, 2004
30
0
0
US
I'm trying to:
1. Get the total bytes of a string.
2. Remove the last 20 bytes of that string
3. Set what is left over to a string.

So far I have only # 1? does anyone know how to do this?
 
Assuming your string is in $_:
Code:
my $length = length($_);
my ($left,$right) = m/^(.*)(.{20})$/;


Trojan.

 
TIMTOWTDI
substr will accept negative parameters, it's not a sweet as the regex, and most likely depends on on a regex, but it will read from the opposite end of a string.
--Paul

cigless ...
 
substr doesn't use regexps at all - just positions in the string. Assuming the string is in $str, this will remove the last 20 characters (note that if you're using Unicode, removing 20 characters isn't the same as 20 bytes).
Code:
substr( $str, -20 ) = '';
 
Code:
[b]#!/usr/bin/perl[/b]

$string = 'How do I remove the last 20 bytes from a string?';

print substr $string, -20, 20;

output... [red]bytes from a string?[/red]


Kind Regards
Duncan
 
Duncan you gave me a great idea,how about this?

$newstring= substr $string,1,$stringlen -20;
 
Newbee - that'd remove the first character too! You need to start your offset at 0 if you want to include the first character too. That code does the same as what I posted (except you're storing it in a new string, rather than removing 20 characters from the string itself. What I posted could be adjusted to store the new substring in $newstring too:
Code:
substr( my $newstring = $str, -20 ) = '';
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top