Gossamer Forum
Home : General : Perl Programming :

combining whitespace reg ex

Quote Reply
combining whitespace reg ex
hi,

is there a way to convert these three statements into one?

$here =~ s|^\s+||gs;
$here =~ s|\s+$||gs;
$here =~ s|\s+|_|gs;

obviously, i want to trim whitespace at the beginning and end, then turn any remaining whitespace+ into a '_'

all the docs i've looked at show elimating whitespace at beginning and end as separate statements.

thanks!
Quote Reply
Re: [adrockjames] combining whitespace reg ex In reply to
Well you "can" combine them into one but it involves a bit of cheating :)

Code:
$here =~ s|^(.*)$|
my $grab = $1;
$grab = substr($grab, index($grab, " ")) if (substr($1,0,1) eq " ");
$grab = substr($grab, 0, rindex($grab, " ")) if (substr($1,-1,1) eq " ");
$grab =~ y/ /_/ if (index($grab, " ") > -1);
|seg;

Laugh

But seriously. You can combine them into two regexs but not one.

Code:
$here =~ s#^\s+|\s+$##sg;
Quote Reply
Re: [Paul] combining whitespace reg ex In reply to
In one regex, eh? I accept that challenge! Smile

How about:
Code:
$here =~ s/(^\s+)|(\s+$)|(\s+)/defined($3)?'_':''/eg

However, I'd not recommend that for maintainable code ...

Cheers,
Dave.
Quote Reply
Re: [utinni] combining whitespace reg ex In reply to
Ah yes, mine looks a little long in comparison :)

Btw, you wouldn't happen to be davorg would you? Wink
Quote Reply
Re: [Paul] combining whitespace reg ex In reply to
Quote:
Btw, you wouldn't happen to be davorg would you?

Sorry, that's not me.
Just found this forum in passing one day, and felt I could be of assistance to some of the posters.

Cheers,
Dave.