Removing leading and trailing spaces only in PERL

Hi All,

I have a file with the following contents with multiple lines

172445957|   000005911|8| 400 Peninsula Ave.#1551  | And,K |935172445957|000005911
607573888  |000098536  | 2|Ane, B |J |Ane |1868 |19861206|20090106|20071001

I want to trim the "leading and trailing spaces only" from each of the field of each line in perl.

For example: I want to remove leading space from " 000005911" and leading and trailing spaces from " 400 Peninsula Ave.#1551 " within the | delimter, not in between spaces of 400 and Peninsula and Ave.

I tried the following code

$data =~ s/^\s/+/;
$data =~ s/\s+$//;

It removes all the spaces from each field of the line.i.e. it gives me the result like for a specific field

from
" 400 Peninsula Ave.#1551 "

to

"400PeninsulaAve.#1551"

But I want like

"400 Peninsula Ave.#1551" no leading and trailing spaces

I just the put quotes for explanation.

Please help me if I can do it perl.

Appreciate your help.

Regards

-Kumar

Option 1:

$data =~ s/\|\s+/g;
$data =~ s/\s+\|/g;

Option 2:

$data = join '|', map { s/\s+$/; s/^\s+/; } split /|/, $data;

option 2 might need a small correction:

 split /|/, $data;

the pipe should be escaped:

 split /\|/, $data;

both are good, I prefer option 1 myself.