Rindex used to find end of a string

P

Paul.Lee.1971

Hi all,
I have a sequence of strings, for instance
"Hello, World "
"My First Perl Test "
"Exit(0) "

- as you can see, the strings are all different lengths. Is there a
way to use rindex to find out the last non-whitespace character in the
string? I'd like to be able to use a general function to return
"Hello, World", "My First Perl Test" and "Exit(0).

Thanks in advance

Paul
 
B

Ben Morrow

Quoth "Paul.Lee.1971 said:
Hi all,
I have a sequence of strings, for instance
"Hello, World "
"My First Perl Test "
"Exit(0) "

- as you can see, the strings are all different lengths. Is there a
way to use rindex to find out the last non-whitespace character in the
string?

Not easily. For a task like this you want a regex. The index of the last
non-whitespace character in a string $str can be found with

$str =~ /(\s*)$/ && length($str) - length($1) - 1;

....
I'd like to be able to use a general function to return
"Hello, World", "My First Perl Test" and "Exit(0).

....but if you just want to remove it you'd be better off doing that in
one step:

$str =~ s/\s*$//;

You need to read up on basic Perl operations: I would recommend you get
a good book.

Ben
 
L

Lambik

Paul.Lee.1971 said:
Hi all,
I have a sequence of strings, for instance
"Hello, World "
"My First Perl Test "
"Exit(0) "

- as you can see, the strings are all different lengths. Is there a
way to use rindex to find out the last non-whitespace character in the
string? I'd like to be able to use a general function to return
"Hello, World", "My First Perl Test" and "Exit(0).
this is a faq

perldoc -q "blank space"

after which you can check the length with:

perldoc -f length
 
A

anno4000

Ben Morrow said:
Not easily. For a task like this you want a regex. The index of the last
non-whitespace character in a string $str can be found with

$str =~ /(\s*)$/ && length($str) - length($1) - 1;

....or

$str =~ /\s*$/ && $-[ 0] - 1;

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top