I am working on a script in which one task is to "squash" strings of certain non-alphanumeric characters (however rare it might be to find two or more of them in a row). Well,<KBD> tr/// </KBD>to the rescue. I first used:

<KBD>tr/,()@+~#$%^&*-{}[]<>\/\|//s;</KBD>

It worked, sort of. But it would change a string such as<KBD> Mississippi </KBD>into<KBD> Misisipi</KBD>.

??? Then it occurred to me that perhaps the presence of the hyphen within the search-list might be making Perl "think" I'd asked for a range. This seemed pretty far-fetched, but I decided I should check the result of escaping the hyphen:

<KBD>tr/,()@+~#$%^&*\-{}[]<>\/\|//s;</KBD>

To my surprise, it worked; punctuation marks were "squashed" as I'd wanted. Repeated alphanumeric characters were left untouched. Moving the hyphen to the very end of the search-list also stopped the unwanted removal of alphanumeric characters.

Why did the hyphen as first used have that effect, when no range resembling<KBD> A-Z </KBD>or<KBD> a-z </KBD>seems to have specified?

As ever, thanks in advance . . .


In reply to Question concerning tr// 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.