Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using literal $ in Regexp 3

Status
Not open for further replies.

Nebbish

Programmer
Apr 7, 2004
73
US
Ok all you smart people, here's one. I want:

Code:
my $bob = 'bob$$$';
if('BOB$$$' =~ /$bob/i) {
	die "happy";
} else {
	die "sad";
}

to die happy. The ignore case flag (/i) seems to freak out when it sees $$$. It doesn't crash, mind you; it just doesn't pass. If I define bob as:

my $bob = 'BOB\$\$\$';

It works. Is there any easier way to get the script to treat $ literally?

Nick
 
it isnt the i that is freaked out grep is trying to use the $ which is a metacharacter for at end of a line. so without the backslash to make it a literal it is looking for something at the end.

ie

$num_apple = grep /^apple$/i, @fruits;
The ^ and $ metacharacters anchor the regular expression to the beginning and end of the string, respectively, so that grep selects apple but not pineapple.

so
my $bob = 'bob$$$';
if('BOB$$$' =~ /BOB[\$]*$/i) {
die "happy";
} else {
die "sad";
}

looks for BOB with any number of $'s at the end
 
Code:
my $bob = 'bob$$$';
if('BOB$$$' =~ /\Q$bob/i) {
  die "happy";
} else {
  die "sad";
}


Kind Regards
Duncan
 
That's what I was looking for...thanks Duncan.

Arcnon--that's a valid point. However, I was having this problem with $ even when it was in the middle of a string, and not at the end. For example:

Code:
my $string = 'hello$$$hi';
if('HELLO$$$hi' =~ /^$string$/i) {
	die "happy";
} else {
	die "sad";
}

Still died sad. The problem was it wasn't treating $ literally. I wanted something to literalize the whole string without putting \ before everything that needed it. \Q does this.

Thanks again guys,

Nick
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top