$line = "one two three four four SIX"; $line =~ s/two/six/; $line =~ s/four/ten/g; $line =~ s/th(re)e/whe$1/ if ($line =~ /six/i) { } #### //================================================ // C++11 Perl equivalency wrapper functions //================================================ #include #include #include #include using namespace std; // Equivalent to Perl: $s =~ s/$e1/$e2/g; inline void StrReplaceXg(string& s, string e1, string e2) { string r = regex_replace(s, regex{e1}, e2); s = r; } // Equivalent to Perl: $s =~ s/$e1/$e2/; inline void StrReplaceX(string& s, string e1, string e2) { string r = regex_replace(s, regex{e1}, e2, regex_constants::format_first_only); s = r; } // Equivalent to Perl: if ($s =~ /$e1/) { /*dosomething with m[0]...*/ } inline bool StrMatchX(string& s, string e1, vector& m) { smatch M; m.clear(); bool rc = regex_match(s, M, regex{e1}); if (rc) { for(int i=1; i < (int) M.size(); i++) { m.push_back(M[i].str()); } } return rc; } //================================================ // Example 1: C++11 vs Perl //================================================ // PERL: //sub example1() { // $s = "one two three four four"; // $s =~ s/two/stuff/; // print "s:$s\n"; //} // C++11: void example1() { string s = string{"one two three four four"}; StrReplaceX (s, R"(two)", "stuff"); cout << "s:" << s << "\n"; } //================================================ // Example 2: C++11 vs Perl //================================================ // PERL: //sub example2() { // $s = "one two three four four"; // $s =~ s/four/stuff/g; // print "s:$s\n"; //} // C++11: void example2() { string s = string{"one two three four four"}; StrReplaceXg (s, R"(four)", "stuff"); cout << "s:" << s << "\n"; } //================================================ // Example 3: C++11 vs Perl //================================================ // PERL: //sub example3() { // $s = "one two three four four"; // if ($s =~ /(\S+) (\S+)/) { // print "match1: $1\n"; // print "match2: $2\n"; // } //} // C++11: void example3() { string s = string{"one two three four four"}; vector m; if (StrMatchX(s, R"((\S+) (\S+))", m)) { cout << "match1:" << m[0] << "\n"; cout << "match2:" << m[1] << "\n"; } } int main(int, char**) { example1(); example2(); example3(); return 0; }