Naidu
Naidu

Reputation: 149

how to check wether a special character "+" is present in a string using perl

I am using an if condition to check if a "+" is present in string. If it is present, it should print some thing, else if "-" is present, it should print some thing else:

if ($test_1 =~/^+/)
{
    print OUTFILE1 "Unsigned \n";
}
elsif($test_1 =~/^-/)
{
    print OUTFILE1 "Signed \n";
}

Upvotes: 0

Views: 204

Answers (3)

Filippo Lauria
Filippo Lauria

Reputation: 2074

You could use the function index() that is intended to determine the position of a character ("+" or "-" in your case) or a substring in a string.

Here you have an example:

 ...
if (index($test_1, "+") == 0) { # check if + is in the 0-th position,
  print OUTFILE1 "Unsigned \n"; # that means the 1-st starting from left;
} elsif (index($test_1, "-") == 0) {
  print OUTFILE1 "Signed \n";
}
 ...

Upvotes: -1

Lee Duhem
Lee Duhem

Reputation: 15121

if ($test_1 =~/^+/)

should be

if ($test_1 =~/^\+/)

+ has special meaning in regular expression, if you want to match it as a normal character, you need to escape it.

Upvotes: 4

anubhava
anubhava

Reputation: 785631

+ needs to be escaped and you probably don't need start anchor:

if ($test_1 =~ /\+/)
{
    print OUTFILE1 "Unsigned \n";
}
elsif ($test_1 =~ /-/)
{
    print OUTFILE1 "Signed \n";
}

Upvotes: 2

Related Questions