5

I am a beginner of perl scripting. I know hyphen (-) is used to specify the range.

But what if it is mentioned in the beginning of the expression?

Example:

if ($_ =~ /-\n/)
//do something

How to interpret the above code?

"if the parameter is equal to a range of newline" ? (No, that is weird understanding :-/)

Please help.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
SS Hegde
  • 729
  • 2
  • 14
  • 33

3 Answers3

7

Outside of [] - means "-" as far as I know, it only indicates a range within a [] block.

Here is a more complete answer I found

How to match hyphens with Regular Expression? (look at the second answer)

So the expression should match a - followed by a newline or line ending with -

Community
  • 1
  • 1
David Mårtensson
  • 7,550
  • 4
  • 31
  • 47
5

The pattern will match hyphens "-" followed by a newline \n.

The hyphen is treated as a range operator inside character classes, as explained in perldoc perlrequick:

The special character '-' acts as a range operator within character classes, so that the unwieldy [0123456789] and [abc...xyz] become the svelte [0-9] and [a-z] :

/item[0-9]/;  # matches 'item0' or ... or 'item9'
/[0-9a-fA-F]/;  # matches a hexadecimal digit

If '-' is the first or last character in a character class, it is treated as an ordinary character.

Zaid
  • 36,680
  • 16
  • 86
  • 155
4

This means:

If there is a hyphen immediately followed by a newline-character, no matter where this pair of characters is located inside the string.

Hubert Schölnast
  • 8,341
  • 9
  • 39
  • 76