Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: how insert back slash to a string that has only special characters or mixture of both

by suhailck (Friar)
on Sep 06, 2010 at 06:10 UTC ( #858996=note: print w/ replies, xml ) Need Help??


in reply to unable to differentiate last word and intermediate word in a sentence

perl -le '$_=q{hi! how are you, man.};s/([!@#$%^&(),.}{[\]+-])/\\$1/g; +print' hi\! how are you\, man\.


Comment on Re: how insert back slash to a string that has only special characters or mixture of both
Download Code
Re^2: how insert back slash to a string that has only special characters or mixture of both
by k_manimuthu (Monk) on Sep 06, 2010 at 08:06 UTC

    The quotemeta function do this.

    $var="!@#$%^&(),.}{[]+-"; print "\n$var"; $var_with_slash=quotemeta($var); print"\n$var_with_slash";
Re^2: how insert back slash to a string that has only special characters or mixture of both
by ww (Bishop) on Sep 06, 2010 at 11:42 UTC
    suhailck:

    That may not be (see "Update") what OP sought: "for each special character in..." a string of special chars (only) .

    Emphasis supplied.

    Update Oops. Apologies to suhailck!

    I missed the fact that the title explicitly allows for a "mixture" (and relied on OP's narrative and example). Hence, suhailck's reply is arguably better than the next, since the second, among other things, will convert #$%^ to #0\^ and escape the spaces, if a string of "words" is inserted in the $var

    my $var="!@#$%^&(),.Now is the time}{[]+-"; print "\n$var"; my $var_with_slash=quotemeta($var); print"\n$var_with_slash";

    outputs:

    !@#0^&(),.Now is the time}{[]+- \!\@\#0\^\&\(\)\,\.Now\ is\ the\ time\}\{\[\]\+\-

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2014-09-18 00:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (101 votes), past polls