Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Perl6 regex substitutions

by kovacsbv (Novice)
on Mar 05, 2014 at 16:28 UTC ( [id://1077103]=perlquestion: print w/replies, xml ) Need Help??

kovacsbv has asked for the wisdom of the Perl Monks concerning the following question:

One thing I'm not finding much about on the web is perl6 regex substitutions, e. g:
Perl 5: $x = "this is a test"; $x =~ s/ /-/;
Anybody know how without invoking P5 compatibility mode?

Replies are listed 'Best First'.
Re: Perl6 regex substitutions
by vinoth.ree (Monsignor) on Mar 05, 2014 at 18:15 UTC
Re: Perl6 regex substitutions
by FROGGS (Novice) on Mar 06, 2014 at 21:19 UTC
    You can also use the method form if you are more a Java(Script) guy:
    use v6; my $x = "this is a test".subst(/\s/, '-', :g); # or my $x = "this is a test"; $x.=subst(/\s/, '-', :g);
    The second example calls the subst method on $x (that's why you see a dot), and then mutates it (the equal sign).

    :g is again the adverb for global matching, like in s:g///.

Re: Perl6 regex substitutions
by linuxer (Curate) on Mar 05, 2014 at 20:51 UTC
Re: Perl6 regex substitutions
by raiph (Deacon) on Mar 06, 2014 at 20:52 UTC
    »»» This post is about the immature Perl 6, not the rock solid Perl 5 «««

    Perl 6:

    my $x = "this is a test"; $x ~~ s:g/\s/-/;

    Notes:

    • P6 uses strict mode by default, so I've added a 'my'.
    • The P6 smartmatch operator (~~) covers many cases including ones covered by =~ in Perl 5.
    • In P6 :g is a regex modifier, in this case making the search/replace global. (In Perl 5 it would have been specified as s///g.)
    • In effect P6 regex all have the equivalent of Perl 5's /x regex modifier set on. You can't switch it off. The \s is one of several whitespace alternatives available.

    If you want any further help regarding Perl 6, I strongly recommend a visit to the IRC channel #perl6 on freenode, but I'all also check in here to see if you post a follow up.

    Hth.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1077103]
Approved by GotToBTru
Front-paged by GotToBTru
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2024-03-29 01:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found