2

This might be a beginners mistake.
The regex turns out always as not matching while clearly it should.

#!/usr/bin/perl 
# This will print "Hello, World"
print "Hello, world\n";
my $addr = "Hello";
#if($addr =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\)/ )
if (my $addr =~ /Hello/)
{
      print("matched\n\n");
}else
{
  print("Didnt Match\n\n");
}
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Rgarg
  • 496
  • 3
  • 6
  • 13

3 Answers3

3

The my makes the variable you match local and uninitialised. So you should change to

if ($addr =~ /Hello/)

The my indicates that the $addr in the if is "my own here", i.e. different from the other $addr the one with larger, outer scope.
Only the outer scope variable got initialised to something which would match your regex. The second, inner one is not initialised and (at least in your case) has no matching value.

Note: Comments by other authors have proposed a best practice for avoiding/detecting the cause of your problem in future programming.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
1

I know this has been answered already, but let me just expand a bit.

in general in perl we would work in blocks, if we can call it that. If you set

my $string = 'String';

in the beginning of the script, outside any loop, that declaration will stay the string throughout the script, unless you re-declare or re-assign it somewhere along the line.

my $string = 'string';
   $string = 'Text';

That changes a bit if you work inside of a block, let's say in an if statement:

Scenario 1.

my $var = 'test';
   if ($var =~ /test/) {
       my $string = 'string';
    }
  print $string;      # This will not work as $string only existed in the if block.

The following is the same scenario, but you re-declare $var in the if block and therefore it will try and match the new variable which has no value and therefore $string in this instance will never be set.

Scenario 2.

my $var = 'test';
   if (my $var =~ /test/) {
       my $string = 'string';
    }

There is another one though which works differently from my and that is our

Scenario 3.

my $var = 'test';
   if ($var =~ /test/) {
       our $string = 'string';
    }
print $string;

The above scenario works a bit different from scenario 1. We are declaring our $string inside of the if statement block and we can now use $string outside of that loop because our is saying any block from here on, owns this variable.

Gerhard
  • 22,678
  • 7
  • 27
  • 43
0

U had initialised another variable called $addr in the scope of if, instead of using the variable which was initialized in the global scope.

#!/usr/bin/perl 
# This will print "Hello, World"
print "Hello, world\n";
my $addr = "Hello";
#if($addr =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\)/ )
if ($addr =~ /Hello/)
{
      print("matched\n\n");
}else
{
  print("Didnt Match\n\n");
}