Substituting strings in a list

G

glvs

Hi,
How can I combine following 2 instructions into one? I want to split
tab delimited input into a list and then right trim every item in that
list.

@list = split("\t", $input);
@list =~ map{ s/\s+$// } @list;

Thanks,
Glenn
 
G

Gunnar Hjalmarsson

How can I combine following 2 instructions into one? I want to split
tab delimited input into a list and then right trim every item in that
list.

@list = split("\t", $input);
@list =~ map{ s/\s+$// } @list;

@list = split ' ', $input;

See "perldoc -f split".
 
G

Gunnar Hjalmarsson

Gunnar said:
@list = split ' ', $input;

Or, to really follow the prerequisites:

@list = map { s/\s+$//; $_ } split /\t/, $input;

(Maybe it's the map() function you should read up about.)
 
B

Bart Lateur

How can I combine following 2 instructions into one? I want to split
tab delimited input into a list and then right trim every item in that
list.

@list = split("\t", $input);
@list =~ map{ s/\s+$// } @list;

The latter won't work. Try a for modifier instead:

s/\s+$// for @list;

As for combining, try a more elaborate regexp for the split:

@list = split / *(?:\t|$)/, $input;

I've added the end of line to the list of allowable delimiters, or else
spaces at the end of the last field wouldn't be removed. Empty trailing
fields are dropped, anyway.

Note that the parens may not be capturing, or else the delimiters will
appear in the output list.
 
G

Gunnar Hjalmarsson

Bart said:
The latter won't work.

Yes, it will, even if the '@list =~' part does not make sense (and,
hence, generates warnings if warnings are enabled).

map { s/\s+$// } @list;

does the work just fine.
 
C

chris-usenet

How can I combine following 2 instructions into one? I want to split
tab delimited input into a list and then right trim every item in that
list.

If it's permissible to assume that your input whitespace will be only
spaces or tabs then the following will work. If you're generalising
the "right trim" requirement to include other whitespace characters
(e.g. vertical tab) then you'll need to extend this appropriately:

@list = split (" *\t", $input);

Chris
 

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
474,177
Messages
2,570,952
Members
47,506
Latest member
tomiy16522

Latest Threads

Top