Monday, August 10, 2009

Use of quote like operators

Various "q" type of functions are mentioned below
  • q/STRING/
  • qq/STRING/
  • qr/STRING/
  • qx/STRING/
  • qw/STRING/
q// or q{} :
It represents single-quoted, literal string. It can be used instead of single quotes( ' '). Here // or {} are delimiters.

qq/ / or qq{ } :
It represents Double-quoted interpolated string. It can be used instead of single quotes( '" ").

e.g.
my $blog = "www.batchandperl.blogspot.com";

print q{ This is my blog: $blog \n}; # prints "This is my blog: $blog \n"

print qq{ This is my blog: $blog \n}; # prints "This is my blog: www.batchandperl.blogspot.com"


qr/STRING/msixpo or qr{ }msixpo :
This operator quotes it's string as regular expression. STRING will be interpolated in the same way as PATTERN in m/PATTERN/. If "'" is used as the delimiter, no interpolation is done. It Returns a Perl value which may be used instead of the corresponding /STRING/msixpo expression.
e.g.
$rex = qr/my.STRING/is;
s/$rex/foo/;

is equivalent to
s/my.STRING/foo/is
;

$re = qr/$pattern/;
$string =~ /foo${re}bar/; # can be interpolated in other patterns
$string =~ $re; # or used standalone
$string
=~ /$re/; # or this way

Options for using qr// are:
  1. m Treat string as multiple lines.
  2. s Treat string as single line. (Make . match a newline)
  3. i Do case-insensitive pattern matching.
  4. x Use extended regular expressions.
  5. p When matching preserve a copy of the matched string so
  6. that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
  7. o Compile pattern only once.

If a precompiled pattern is embedded in a larger pattern then the effect of 'msixp' will be propagated appropriately. The effect of the 'o' modifier has is not propagated, being restricted to those patterns explicitly using it.


qx/ / or qx{ } :
It's an alternative to using back quotes to execute system commands. It's equivalent to ( ` ` ).
e.g.
my @dir_out = qx{dir};
print @dir; #prints returned value by executing `dir` command on shell.


qw/STRING / or qw{};
It's a quick way to specify multiple single quoted words present in STRING and delimited by white space. Simply you can use qw() to create an array. It returns a list consisting of elements of LIST as they were single quoted.

It's equivalent to
 split(' ', q/STRING/);

e.g.
qw(foo bar baz); is equivalent to ('foo', 'bar', 'baz')

A very common mistake in STRING is to try to separate words with comma or to put comments
into multi-line qw() string. For this, pragma use warnings ; produces warnings.

quotemeta EXPR:
It returns a string with all meta characters escaped.
For example, quotemeta("AB*..C") returns "AB\*\.\.C".


print quotemeta("AB*\n[.]*");
#returns
AB\*\
\[\.\]\*

No comments:

Post a Comment