If you want to replace with literal brackets, you need to escape the brackets with the backslash character ("\"):

s/.+/$bef[$mid$aft/: (SYNTAX ERROR: "scalar found where operator expected"...)

should be written as:

s/.+/$bef\[$mid$aft/;

There are many characters that need to be escaped in regular expressions. The bracket could be interpreted either as the beginning and end of a character class ( example [a-z]), or as a subscript for an array (example: $bef[4]). In this case it's probably the later, since I don't think perl can make any sense out of a character class in a replacement expression. By putting a backslash in front of the bracket it looses its special meaning. Some other characters that have a special meaning are $," and /.

Then there are other perfectly normal characters that take on a special meaning when preceded by a backslash in a regular expression, e.g. \d (digit character), \s (any whitespace character), \S (anything that isn't a white space character).

The place to look for this kind of information is the perlre section of the perl man pages. If you're on Unix or similar, type "man perlre" at the command line (without the quotes). If you're on windows click the perlre link in the HTML documentation.

Hope this helps, /jeorgen


In reply to RE: Regexp: not what I'd expected by jeorgen
in thread Regexp: not what I'd expected by greenhorn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.