XX X X X X XX<'> X<''> X<"> X<""> X/> X<`> X<``> X<<< << >>> X X While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of them. In the following table, a C<{}> represents any pair of delimiters you choose. Customary Generic Meaning Interpolates '' q{} Literal no "" qq{} Literal yes `` qx{} Command yes* qw{} Word list no // m{} Pattern match yes* qr{} Pattern yes* s{}{} Substitution yes* tr{}{} Transliteration no (but see below) y{}{} Transliteration no (but see below) < > module (standard as of v5.8, and from CPAN before then) is able to do this properly. There can (and in some cases, must) be whitespace between the operator and the quoting characters, except when C<#> is being used as the quoting character. C is parsed as the string C, while S > is the operator C X X Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string). If the C (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when C is used. The copy will always be a plain string, even if the input is an object or a tied variable. If no string is specified via the C<=~> or C operator, the C<$_> variable is searched and modified. Unless the C option is used, the string specified must be a scalar variable, an array element, a hash element, or an assignment to one of those; that is, some sort of scalar lvalue. If the delimiter chosen is a single quote, no variable interpolation is done on either the Ifollowed by a comment. Its argument will be taken from the next line. This allows you to write: s {foo} # Replace foo {bar} # with bar. The cases where whitespace must be used are when the quoting character is a word character (meaning it matches C\w/>): q XfooX # Works: means the string 'foo' qXfooX # WRONG! The following escape sequences are available in constructs that interpolate, and in transliterations: X<\t> X<\n> X<\r> X<\f> X<\b> X<\a> X<\e> X<\x> X<\0> X<\c> X<\N> X<\N{}> X<\o{}> Sequence Note Description \t tab (HT, TAB) \n newline (NL) \r return (CR) \f form feed (FF) \b backspace (BS) \a alarm (bell) (BEL) \e escape (ESC) \x{263A} [1,8] hex char (example: SMILEY) \x1b [2,8] restricted range hex char (example: ESC) \N{name} [3] named Unicode character or character sequence \N{U+263D} [4,8] Unicode character (example: FIRST QUARTER MOON) \c[ [5] control char (example: chr(27)) \o{23072} [6,8] octal char (example: SMILEY) \033 [7,8] restricted range octal char (example: ESC) =over 4 =item [1] The result is the character specified by the hexadecimal number between the braces. See L[8]> below for details on which character. Only hexadecimal digits are valid between the braces. If an invalid character is encountered, a warning will be issued and the invalid character and all subsequent characters (valid or invalid) within the braces will be discarded. If there are no valid digits between the braces, the generated character is the NULL character (C<\x{00}>). However, an explicit empty brace (C<\x{}>) will not cause a warning (currently). =item [2] The result is the character specified by the hexadecimal number in the range 0x00 to 0xFF. See L[8]> below for details on which character. Only hexadecimal digits are valid following C<\x>. When C<\x> is followed by fewer than two valid digits, any valid digits will be zero-padded. This means that C<\x7> will be interpreted as C<\x07>, and a lone C<"\x"> will be interpreted as C<\x00>. Except at the end of a string, having fewer than two valid digits will result in a warning. Note that although the warning says the illegal character is ignored, it is only ignored as part of the escape and will still be used as the subsequent character in the string. For example: Original Result Warns? "\x7" "\x07" no "\x" "\x00" no "\x7q" "\x07q" yes "\xq" "\x00q" yes =item [3] The result is the Unicode character or character sequence given by I. See L . =item [4] S }>> means the Unicode character whose Unicode code point is I modifier (for example, C. =item [5] The character following C<\c> is mapped to some other character as shown in the table: Sequence Value \c@ chr(0) \cA chr(1) \ca chr(1) \cB chr(2) \cb chr(2) ... \cZ chr(26) \cz chr(26) \c[ chr(27) # See below for chr(28) \c] chr(29) \c^ chr(30) \c_ chr(31) \c? chr(127) # (on ASCII platforms; see below for link to # EBCDIC discussion) In other words, it's the character whose code point has had 64 xor'd with its uppercase. C<\c?> is DELETE on ASCII platforms because S > is 127, and C<\c@> is NULL because the ord of C<"@"> is 64, so xor'ing 64 itself produces 0. Also, C<\c\I =item C/msixpodualngc> Searches a string for a pattern match, and in scalar context returns true if it succeeds, false if it fails. If no string is specified via the C<=~> or C operator, the C<$_> string is searched. (The string specified with C<=~> need not be an lvalue--it may be the result of an expression evaluation, but remember the C<=~> binds rather tightly.) See also L> yields S X X X X">> for any I , but cannot come at the end of a string, because the backslash would be parsed as escaping the end quote. On ASCII platforms, the resulting characters from the list above are the complete set of ASCII controls. This isn't the case on EBCDIC platforms; see L X This operator quotes (and possibly compiles) its Ifor a full discussion of the differences between these for ASCII versus EBCDIC platforms. Use of any other character following the C<"c"> besides those listed above is discouraged, and as of Perl v5.20, the only characters actually allowed are the printable ASCII ones, minus the left brace C<"{">. What happens for any of the allowed other characters is that the value is derived by xor'ing with the seventh bit, which is 64, and a warning raised if enabled. Using the non-allowed characters generates a fatal error. To get platform independent controls, you can use C<\N{...}>. =item [6] The result is the character specified by the octal number between the braces. See L[8]> below for details on which character. If a character that isn't an octal digit is encountered, a warning is raised, and the value is based on the octal digits before it, discarding it and all following characters up to the closing brace. It is a fatal error if there are no octal digits at all. =item [7] The result is the character specified by the three-digit octal number in the range 000 to 777 (but best to not use above 077, see next paragraph). See L[8]> below for details on which character. Some contexts allow 2 or even 1 digit, but any usage without exactly three digits, the first being a zero, may give unintended results. (For example, in a regular expression it may be confused with a backreference; see L .) Starting in Perl 5.14, you may use C<\o{}> instead, which avoids all these problems. Otherwise, it is best to use this construct only for ordinals C<\077> and below, remembering to pad to the left with zeros to make three digits. For larger ordinals, either use C<\o{}>, or convert to something else, such as to hex and use C<\N{U+}> (which is portable between platforms with different character sets) or C<\x{}> instead. =item [8] Several constructs above specify a character by a number. That number gives the character's position in the character set encoding (indexed from 0). This is called synonymously its ordinal, code position, or code point. Perl works on platforms that have a native encoding currently of either ASCII/Latin1 or EBCDIC, each of which allow specification of 256 characters. In general, if the number is 255 (0xFF, 0377) or below, Perl interprets this in the platform's native encoding. If the number is 256 (0x100, 0400) or above, Perl interprets it as a Unicode code point and the result is the corresponding Unicode character. For example C<\x{50}> and C<\o{120}> both are the number 80 in decimal, which is less than 256, so the number is interpreted in the native character set encoding. In ASCII the character in the 80th position (indexed from 0) is the letter C<"P">, and in EBCDIC it is the ampersand symbol C<"&">. C<\x{100}> and C<\o{400}> are both 256 in decimal, so the number is interpreted as a Unicode code point no matter what the native encoding is. The name of the character in the 256th position (indexed by 0) in Unicode is C . An exception to the above rule is that S }>> is always interpreted as a Unicode code point, so that C<\N{U+0050}> is C<"P"> even on EBCDIC platforms. =back B : Unlike C and other languages, Perl has no C<\v> escape sequence for the vertical tab (VT, which is 11 in both ASCII and EBCDIC), but you may use C<\N{VT}>, C<\ck>, C<\N{U+0b}>, or C<\x0b>. (C<\v> does have meaning in regular expression patterns in Perl, see L .) The following escape sequences are available in constructs that interpolate, but not in transliterations. X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q> X<\F> \l lowercase next character only \u titlecase (not uppercase!) next character only \L lowercase all characters till \E or end of string \U uppercase all characters till \E or end of string \F foldcase all characters till \E or end of string \Q quote (disable) pattern metacharacters till \E or end of string \E end either case modification or quoted section (whichever was last seen) See L for the exact definition of characters that are quoted by C<\Q>. C<\L>, C<\U>, C<\F>, and C<\Q> can stack, in which case you need one C<\E> for each. For example: say"This \Qquoting \ubusiness \Uhere isn't quite\E done yet,\E is it?"; This quoting\ Business\ HERE\ ISN\'T\ QUITE\ done\ yet\, is it? If a S > form that includes C is in effect (see L ), the case map used by C<\l>, C<\L>, C<\u>, and C<\U> is taken from the current locale. If Unicode (for example, C<\N{}> or code points of 0x100 or beyond) is being used, the case map used by C<\l>, C<\L>, C<\u>, and C<\U> is as defined by Unicode. That means that case-mapping a single character can sometimes produce a sequence of several characters. Under S >, C<\F> produces the same results as C<\L> for all locales but a UTF-8 one, where it instead uses the Unicode definition. All systems use the virtual C<"\n"> to represent a line terminator, called a "newline". There is no such thing as an unvarying, physical newline character. It is only an illusion that the operating system, device drivers, C libraries, and Perl all conspire to preserve. Not all systems read C<"\r"> as ASCII CR and C<"\n"> as ASCII LF. For example, on the ancient Macs (pre-MacOS X) of yesteryear, these used to be reversed, and on systems without a line terminator, printing C<"\n"> might emit no actual data. In general, use C<"\n"> when you mean a "newline" for your system, but use the literal ASCII when you need an exact character. For example, most networking protocols expect and prefer a CR+LF (C<"\015\012"> or C<"\cM\cJ">) for line terminators, and although they often accept just C<"\012">, they seldom tolerate just C<"\015">. If you get in the habit of using C<"\n"> for networking, you may be burned some day. X X X X X<\n> X<\r> X<\r\n> For constructs that do interpolate, variables beginning with "C<$>" or "C<@>" are interpolated. Subscripted variables such as C<$a[3]> or C<< $href->{key}[0] >> are also interpolated, as are array and hash slices. But method calls such as C<< $obj->meth >> are not. Interpolating an array or slice interpolates the elements in order, separated by the value of C<$">, so is equivalent to interpolating S >. "Punctuation" arrays such as C<@*> are usually interpolated only if the name is enclosed in braces C<@{*}>, but the arrays C<@_>, C<@+>, and C<@-> are interpolated even without braces. For double-quoted strings, the quoting from C<\Q> is applied after interpolation and escapes are processed. "abc\Qfoo\tbar$s\Exyz" is equivalent to "abc" . quotemeta("foo\tbar$s") . "xyz" For the pattern of regex operators (C , C and C ), the quoting from C<\Q> is applied after interpolation is processed, but before escapes are processed. This allows the pattern to match literally (except for C<$> and C<@>). For example, the following matches: '\s\t' =~ /\Q\s\t/ Because C<$> or C<@> trigger interpolation, you'll need to use something like C\Quser\E\@\Qhost/> to match them literally. Patterns are subject to an additional level of interpretation as a regular expression. This is done as a second pass, after variables are interpolated, so that regular expressions may be incorporated into the pattern from the variables. If this is not what you want, use C<\Q> to interpolate a variable literally. Apart from the behavior described above, Perl does not expand multiple levels of interpolation. In particular, contrary to the expectations of shell programmers, back-quotes do Iinterpolate within double quotes, nor do single quotes impede evaluation of variables when used within double quotes. =head2 Regexp Quote-Like Operators X Here are the quote-like operators that apply to pattern matching and related activities. =over 8 =item C /msixpodualn> X X X X X X as a regular expression. I is interpolated the same way as I in C />. If C<"'"> is used as the delimiter, no variable interpolation is done. Returns a Perl value which may be used instead of the corresponding C/msixpodualn> expression. The returned value is a normalized version of the original pattern. It magically differs from a string containing the same characters: C returns "Regexp"; however, dereferencing it is not well defined (you currently get the normalized version of the original pattern, but this may change). For example, $rex = qr/my.STRING/is; print $rex; # prints (?si-xm:my.STRING) s/$rex/foo/; is equivalent to s/my.STRING/foo/is; The result may be used as a subpattern in a match: $re = qr/$pattern/; $string =~ /foo${re}bar/; # can be interpolated in other # patterns $string =~ $re; # or used standalone $string =~ /$re/; # or this way Since Perl may compile the pattern at the moment of execution of the C operator, using C may have speed advantages in some situations, notably if the result of C is used standalone: sub match { my $patterns = shift; my @compiled = map qr/$_/i, @$patterns; grep { my $success = 0; foreach my $pat (@compiled) { $success = 1, last if /$pat/; } $success; } @_; } Precompilation of the pattern into an internal representation at the moment of C avoids the need to recompile the pattern every time a match C$pat/> is attempted. (Perl has many other internal optimizations, but none would be triggered in the above example if we did not use C operator.) Options (specified by the following modifiers) are: m Treat string as multiple lines. s Treat string as single line. (Make . match a newline) i Do case-insensitive pattern matching. x Use extended regular expressions; specifying two x's means \t and the SPACE character are ignored within square-bracketed character classes p When matching preserve a copy of the matched string so that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined (ignored starting in v5.20) as these are always defined starting in that release o Compile pattern only once. a ASCII-restrict: Use ASCII for \d, \s, \w and [[:posix:]] character classes; specifying two a's adds the further restriction that no ASCII character will match a non-ASCII one under /i. l Use the current run-time locale's rules. u Use Unicode rules. d Use Unicode or native charset, as in 5.12 and earlier. n Non-capture mode. Don't let () fill in $1, $2, etc... If a precompiled pattern is embedded in a larger pattern then the effect of C<"msixpluadn"> will be propagated appropriately. The effect that the C modifier has is not propagated, being restricted to those patterns explicitly using it. The last four modifiers listed above, added in Perl 5.14, control the character set rules, but C is the only one you are likely to want to specify explicitly; the other three are selected automatically by various pragmas. See L for additional information on valid syntax for I , and for a detailed look at the semantics of regular expressions. In particular, all modifiers except the largely obsolete C are further explained in L . C is described in the next section. =item C /msixpodualngc> X X X X XX X X X X . Options are as described in C above; in addition, the following match process modifiers are available: g Match globally, i.e., find all occurrences. c Do not reset search position on a failed match when /g is in effect. If C<"/"> is the delimiter then the initial C is optional. With the C you can use any pair of non-whitespace (ASCII) characters as delimiters. This is particularly useful for matching path names that contain C<"/">, to avoid LTS (leaning toothpick syndrome). If C<"?"> is the delimiter, then a match-only-once rule applies, described in C ?> below. If C<"'"> (single quote) is the delimiter, no variable interpolation is performed on the I . When using a delimiter character valid in an identifier, whitespace is required after the C . I may contain variables, which will be interpolated every time the pattern search is evaluated, except for when the delimiter is a single quote. (Note that C<$(>, C<$)>, and C<$|> are not interpolated because they look like end-of-string tests.) Perl will not recompile the pattern unless an interpolated variable that it contains changes. You can force Perl to skip the test and never recompile by adding a C (which stands for "once") after the trailing delimiter. Once upon a time, Perl would recompile regular expressions unnecessarily, and this modifier was useful to tell it not to do so, in the interests of speed. But now, the only reasons to use C are one of: =over =item 1 The variables are thousands of characters long and you know that they don't change, and you need to wring out the last little bit of speed by having Perl skip testing for that. (There is a maintenance penalty for doing this, as mentioning C constitutes a promise that you won't change the variables in the pattern. If you do change them, Perl won't even notice.) =item 2 you want the pattern to use the initial values of the variables regardless of whether they change or not. (But there are saner ways of accomplishing this than using C.) =item 3 If the pattern contains embedded code, such as use re 'eval'; $code = 'foo(?{ $x })'; /$code/ then perl will recompile each time, even though the pattern string hasn't changed, to ensure that the current value of C<$x> is seen each time. Use C if you want to avoid this. =back The bottom line is that using C is almost never a good idea. =item The empty pattern C/> If the I evaluates to the empty string, the last I matched regular expression is used instead. In this case, only the C and C option is not used, Cflags on the empty pattern are honored; the other flags are taken from the original pattern. If no match has previously succeeded, this will (silently) act instead as a genuine empty pattern (which will always match). Note that it's possible to confuse Perl into thinking C/> (the empty regex) is really C/> (the defined-or operator). Perl is usually pretty good about this, but some pathological cases might trigger this, such as C<$x///> (is that S > or S >?) and S > (S > or S >?). In all of these examples, Perl will assume you meant defined-or. If you meant the empty regex, just use parentheses or spaces to disambiguate, or even prefix the empty regex with an C (so C/> becomes C ). =item Matching in list context If the C in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, that is, (C<$1>, C<$2>, C<$3>...) (Note that here C<$1> etc. are also set). When there are no parentheses in the pattern, the return value is the list C<(1)> for success. With or without parentheses, an empty list is returned upon failure. Examples: open(TTY, "+ =~ /^y/i && foo(); # do foo if desired if (/Version: *([0-9.]*)/) { $version = $1; } next if m#^/usr/spool/uucp#; # poor man's grep $arg = shift; while (<>) { print if /$arg/o; # compile only once (no longer needed!) } if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/)) This last example splits C<$foo> into the first two words and the remainder of the line, and assigns those three fields to C<$F1>, C<$F2>, and C<$Etc>. The conditional is true if any variables were assigned; that is, if the pattern matched. The C modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern. In scalar context, each execution of C finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the C function; see L . A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the C ). Modifying the target string also resets the search position. =item C<\G I > You can intermix C matches with C , where C<\G> is a zero-width assertion that matches the exact position where the previous C , if any, left off. Without the C modifier, the C<\G> assertion still anchors at C as it was at the start of the operation (see L ), but the match is of course only attempted once. Using C<\G> without C on a target string that has not previously had a C match applied to it is the same as using the C<\A> assertion to match the beginning of the string. Note also that, currently, C<\G> is only properly supported when anchored at the very beginning of the pattern. Examples: # list context ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g); # scalar context local $/ = ""; while ($paragraph = <>) { while ($paragraph =~ /\p{Ll}['")]*[.!?]+['")]*\s/g) { $sentences++; } } say $sentences; Here's another way to check for sentences in a paragraph: my $sentence_rx = qr{ (?: (?<= ^ ) | (?<= \s ) ) # after start-of-string or # whitespace \p{Lu} # capital letter .*? # a bunch of anything (?<= \S ) # that ends in non- # whitespace (?) { say "NEW PARAGRAPH"; my $count = 0; while ($paragraph =~ /($sentence_rx)/g) { printf "\tgot sentence %d: <%s>\n", ++$count, $1; } } Here's how to use C with C<\G>: $_ = "ppooqppqq"; while ($i++ < 2) { print "1: '"; print $1 while /(o)/gc; print "', pos=", pos, "\n"; print "2: '"; print $1 if /\G(q)/gc; print "', pos=", pos, "\n"; print "3: '"; print $1 while /(p)/gc; print "', pos=", pos, "\n"; } print "Final: '$1', pos=",pos,"\n" if /\G(.)/; The last example should print: 1: 'oo', pos=4 2: 'q', pos=5 3: 'pp', pos=7 1: '', pos=7 2: 'q', pos=8 3: '', pos=8 Final: 'q', pos=8 Notice that the final match matched C instead of C, which a match without the C<\G> anchor would have done. Also note that the final match did not update C
. C is only updated on a C match. If the final match did indeed match C , it's a good bet that you're running a very old (pre-5.6.0) version of Perl. A useful idiom for C
X X X-like scanners is C\G.../gc>. You can combine several regexps like this to process a string part-by-part, doing different actions depending on which regexp matched. Each regexp tries to match where the previous one leaves off. $_ = <<'EOL'; $url = URI::URL->new( "http://example.com/" ); die if $url eq "xXx"; EOL LOOP: { print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc; print(" lowercase"), redo LOOP if /\G\p{Ll}+\b[,.;]?\s*/gc; print(" UPPERCASE"), redo LOOP if /\G\p{Lu}+\b[,.;]?\s*/gc; print(" Capitalized"), redo LOOP if /\G\p{Lu}\p{Ll}+\b[,.;]?\s*/gc; print(" MiXeD"), redo LOOP if /\G\pL+\b[,.;]?\s*/gc; print(" alphanumeric"), redo LOOP if /\G[\p{Alpha}\pN]+\b[,.;]?\s*/gc; print(" line-noise"), redo LOOP if /\G\W+/gc; print ". That's all!\n"; } Here is the output (split into several lines): line-noise lowercase line-noise UPPERCASE line-noise UPPERCASE line-noise lowercase line-noise lowercase line-noise lowercase lowercase line-noise lowercase lowercase line-noise lowercase lowercase line-noise MiXeD line-noise. That's all! =item C ?msixpodualngc> X> X This is just like the C /> search, except that it matches only once between calls to the C operator. This is a useful optimization when you want to see only the first occurrence of something in each file of a set of files, for instance. Only C patterns local to the current package are reset. while (<>) { if (m?^$?) { # blank line between header and body } } continue { reset if eof; # clear m?? status for next file } Another example switched the first "latin1" encoding it finds to "utf8" in a pod file: s//utf8/ if m? ^ =encoding \h+ \K latin1 ?x; The match-once behavior is controlled by the match delimiter being C>; with any other delimiter this is the normal C operator. In the past, the leading C in C ?> was optional, but omitting it would produce a deprecation warning. As of v5.22.0, omitting it produces a syntax error. If you encounter this construct in older code, you can just add C . =item C X X X X/I/msixpodualngcer> X XX X X X X or the I . Otherwise, if the I contains a C<$> that looks like a variable rather than an end-of-string test, the variable will be interpolated into the pattern at run-time. If you want the pattern compiled only once the first time the variable is interpolated, use the C option. If the pattern evaluates to the empty string, the last successfully executed regular expression is used instead. See L for further explanation on these. Options are as with C with the addition of the following replacement specific options: e Evaluate the right side as an expression. ee Evaluate the right side as a string then eval the result. r Return substitution and leave the original string untouched. Any non-whitespace delimiter may replace the slashes. Add space after the C when using a character allowed in identifiers. If single quotes are used, no interpretation is done on the replacement string (the C modifier overrides this, however). Note that Perl treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the Iis delimited by bracketing quotes, the I has its own pair of quotes, which may or may not be bracketing quotes, for example, C or C<< s/bar/ >>. A C will cause the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second C modifier will cause the replacement portion to be C ed before being run as a Perl expression. Examples: s/\bgreen\b/mauve/g; # don't change wintergreen $path =~ s|/usr/bin|/usr/local/bin|; s/Login: $foo/Login: $bar/; # run-time pattern ($foo = $bar) =~ s/this/that/; # copy first, then # change ($foo = "$bar") =~ s/this/that/; # convert to string, # copy, then change $foo = $bar =~ s/this/that/r; # Same as above using /r $foo = $bar =~ s/this/that/r =~ s/that/the other/r; # Chained substitutes # using /r @foo = map { s/this/that/r } @bar # /r is very useful in # maps $count = ($paragraph =~ s/Mister\b/Mr./g); # get change-cnt $_ = 'abc123xyz'; s/\d+/$&*2/e; # yields 'abc246xyz' s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz' s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz' s/%(.)/$percent{$1}/g; # change percent escapes; no /e s/%(.)/$percent{$1} || $&/ge; # expr now, so /e s/^=(\w+)/pod($1)/ge; # use function call $_ = 'abc123xyz'; $x = s/abc/def/r; # $x is 'def123xyz' and # $_ remains 'abc123xyz'. # expand variables in $_, but dynamics only, using # symbolic dereferencing s/\$(\w+)/${$1}/g; # Add one to the value of any numbers in the string s/(\d+)/1 + $1/eg; # Titlecase words in the last 30 characters only substr($str, -30) =~ s/\b(\p{Alpha}+)\b/\u\L$1/g; # This will expand any embedded scalar variable # (including lexicals) in $_ : First $1 is interpolated # to the variable name, and then evaluated s/(\$\w+)/$1/eeg; # Delete (most) C comments. $program =~ s { /\* # Match the opening delimiter. .*? # Match a minimal number of characters. \*/ # Match the closing delimiter. } []gsx; s/^\s*(.*?)\s*$/$1/; # trim whitespace in $_, # expensively for ($variable) { # trim whitespace in $variable, # cheap s/^\s+//; s/\s+$//; } s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields Note the use of C<$> instead of C<\> in the last example. Unlike B , we use the \> form only in the left hand side. Anywhere else it's $>. Occasionally, you can't use just a C to get all the changes to occur that you might want. Here are two common cases: # put commas in the right places in an integer 1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g; # expand tabs to 8-column spacing 1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e; =back =head2 Quote-Like Operators X =over 4 =item C /> XXX<'> X<''> =item C<'I'> A single-quoted, literal string. A backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated. $foo = q!I said, "You said, 'She said it.'"!; $bar = q('This is it.'); $baz = '\n'; # a two-character string =item C /> X X X<"> X<""> =item "I" A double-quoted, interpolated string. $_ .= qq (*** The previous line contains the naughty word "$1".\n) if /\b(tcl|java|python)\b/i; # :-) $baz = "\n"; # a one-character string =item C /> X X<`> X<``> X =item C<`I `> A string which is (possibly) interpolated and then executed as a system command with F or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected. In scalar context, it comes back as a single (potentially multi-line) string, or C if the command failed. In list context, returns a list of lines (however you've defined lines with C<$/> or C<$INPUT_RECORD_SEPARATOR>), or an empty list if the command failed. Because backticks do not affect standard error, use shell file descriptor syntax (assuming the shell supports this) if you care to address this. To capture a command's STDERR and STDOUT together: $output = `cmd 2>&1`; To capture a command's STDOUT but discard its STDERR: $output = `cmd 2>/dev/null`; To capture a command's STDERR but discard its STDOUT (ordering is important here): $output = `cmd 2>&1 1>/dev/null`; To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out the old STDERR: $output = `cmd 3>&1 1>&2 2>&3 3>&-`; To read both a command's STDOUT and its STDERR separately, it's easiest to redirect them separately to files, and then read from those files when the program is done: system("program args 1>program.stdout 2>program.stderr"); The STDIN filehandle used by the command is inherited from Perl's STDIN. For example: open(SPLAT, "stuff") || die "can't open stuff: $!"; open(STDIN, "<&SPLAT") || die "can't dupe SPLAT: $!"; print STDOUT `sort`; will print the sorted contents of the file named F<"stuff">. Using single-quote as a delimiter protects the command from Perl's double-quote interpolation, passing it on to the shell instead: $perl_info = qx(ps $$); # that's Perl's $$ $shell_info = qx'ps $$'; # that's the new shell's $$ How that string gets evaluated is entirely subject to the command interpreter on your system. On most platforms, you will have to protect shell metacharacters if you want them treated literally. This is in practice difficult to do, as it's unclear how to escape which characters. See L for a clean and safe example of a manual C and C to emulate backticks safely. On some platforms (notably DOS-like ones), the shell may not be capable of dealing with multiline commands, so putting newlines in the string may not get you what you want. You may be able to evaluate multiple commands in a single line by separating them with the command separator character, if your shell supports that (for example, C<;> on many Unix shells and C<&> on the Windows NT C shell). Perl will attempt to flush all files opened for output before starting the child process, but this may not be supported on some platforms (see L ). To be safe, you may need to set C<$|> (C<$AUTOFLUSH> in C >) or call the C method of C > on any open handles. Beware that some command shells may place restrictions on the length of the command line. You must ensure your strings don't exceed this limit after any necessary interpolations. See the platform-specific release notes for more details about your particular environment. Using this operator can lead to programs that are difficult to port, because the shell commands called vary between systems, and may in fact not be present at all. As one example, the C command under the POSIX shell is very different from the C command under DOS. That doesn't mean you should go out of your way to avoid backticks when they're the right way to get something done. Perl was made to be a glue language, and one of the things it glues together is commands. Just understand what you're getting yourself into. Like C , backticks put the child process exit code in C<$?>. If you'd like to manually inspect failure, you can check all possible failure modes by inspecting C<$?> like this: if ($? == -1) { print "failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n", $? >> 8; } Use the L pragma to control the I/O layers used when reading the output of the command, for example: use open IN => ":encoding(UTF-8)"; my $x = `cmd-producing-utf-8`; See L"I/O Operators"> for more discussion. =item C /> X X XEvaluates to a list of the words extracted out of I, using embedded whitespace as the word delimiters. It can be understood as being roughly equivalent to: split(" ", q/STRING/); the differences being that it generates a real list at compile time, and in scalar context it returns the last element in the list. So this expression: qw(foo bar baz) is semantically equivalent to the list: "foo", "bar", "baz" Some frequently seen examples: use POSIX qw( setlocale localeconv ) @EXPORT = qw( foo bar baz ); A common mistake is to try to separate the words with commas or to put comments into a multi-line C -string. For this reason, the S > pragma and the B<-w> switch (that is, the C<$^W> variable) produces warnings if the I contains the C<","> or the C<"#"> character. =item C /I /cdsr> X X X