Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: remove spaces after join operation

by AnomalousMonk (Canon)
on Jul 26, 2013 at 14:41 UTC ( #1046525=note: print w/ replies, xml ) Need Help??

in reply to remove spaces after join operation

Others have noted the approach of join-ing a list of strings with a space and then taking spaces out of the string where appropriate. Conceptually, the other approach is to not put in a space in the first place. See List::Util::reduce().

>perl -wMstrict -le "my @first_sentence = qw{ i am 2 ( but ) . }; printf qq{'$_' } for @first_sentence; print ''; ;; my $ns = qr{ [().] }xms; ;; my $sentence = join q{ }, @first_sentence; print qq{'$sentence'}; ;; $sentence =~ s{ [ ] (?= $ns) | (?<= $ns) [ ] }''xmsg; print qq{'$sentence'}; ;; ;; use List::Util qw(reduce); ;; $sentence = ''; $sentence = reduce { ($a =~ $ns || $b =~ $ns) ? qq{$a$b} : qq{$a $b} } @first_sentence ; print qq{'$sentence'} " 'i' 'am' '2' '(' 'but' ')' '.' 'i am 2 ( but ) .' 'i am 2(but).' 'i am 2(but).'

Update: Actually, this is what 2teez already did here.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1046525]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2016-08-23 22:13 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (331 votes). Check out past polls.