简体   繁体   中英

Slashes and hashes in Perl and metacharacters

I'd asked earlier about escaping special characters and understand the rules around // and ## yet the example below doesn't work and by my understanding I need to escape, the escape character. It's being searched for as match for it's usual meaning of \\ between the names. I'm stumped. Please help. This has me in knots, despite probably appearing easy to the masses.I know I could have written it as $userInfo =~ #\\#;

#!C:\strawberry\perl\bin\perl.exe

#strict
#diagnostics


$userInfo = "firstname\middlename\lastname.";


if($userInfo =~ m/\\/){ 
print("Found it");
}

else{
print("No match found");
}

这里的问题是,您还必须在$userInfo分配中转义反斜杠:

$userInfo = "firstname\\middlename\\lastname.";

You are trying to search a string which contains the literal bakslash character \\ . Double quotes interpolate. Use single quotes instead.

use warnings;
use strict;

my $userInfo = 'firstname\middlename\lastname.';

if ($userInfo =~ m/\\/){
    print("Found it");
}
else{
    print("No match found");
}

The warnings pragma would have generated a warning message.

See also: Quote and Quote-like Operators

I agree with toolic, if you can, use single quotes.
It will save some preprocessing time needed for string interpolation.

However, if you really need to escape special characters, you can write it like this:

  #!C:\strawberry\perl\bin\perl.exe

  #strict
  #diagnostics

  $userInfo = "firstname\\middlename\\lastname.";      #please note escaped backslahes
  if($userInfo =~ m/\\/)
  { 
    print("Found it");
  }
  else
  {
    print("No match found");
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM