#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    2
    Rep Power
    0

    Question How to do pattern matching


    Hi, This is a simple question, but a small change.

    while( my $line = <$info>) {

    if ($line =~ /sandy/) { print ("SANDY\n");}
    else {print("$line");}
    }
    This is code that matches lines having sandy and prints SANDY else it prints the line as it is. BUT what if my pattern /sandy/ is in a variable $var = sandy and i dont know its value until i print it.
    I tried the following, but its not working.
    while( my $line = <$info>) {

    if ($line =~ /$var/) { print ("SANDY\n");}
    else {print("$line");}
    }

    Plz help me out. Thanks in advance
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    776
    Rep Power
    495
    It works for me, as shown in the following session under the Perl debugger:
    Code:
      DB<1> $var = "sandy";
    
      DB<2> $line = " foe bar sandy baz "
    
      DB<3> print "SANDY\n" if $line =~ /$var/
    SANDY
    What you you have exactly in $var?

IMN logo majestic logo threadwatch logo seochat tools logo