user3264858
user3264858

Reputation: 51

Perl regex pattern match with saved variable

I need to do pattern match with two variables one contains the string and the other contains the regex pattern I tried with the following program

#!/usr/bin/perl
my $name = "sathish.java";
my $other = '*.java';
if ( $name =~ m/$other/ )
{
  print "sathish";

 }

kindly help where am missing

Thanks Sathishkumar

Upvotes: 0

Views: 136

Answers (4)

user2788240
user2788240

Reputation: 39

I like Shmuel's answer, but I'm guessing you probably want to capture the first part of the regex into variable as well?

if so, use

my $other = '\.java$';
if ($name =~ m/(\D*)$other/) {
  print $1;
# prints "sathish"
}

Upvotes: 0

codeninja.sj
codeninja.sj

Reputation: 4119

you can use following style which is more appropriate of your need

$other = "*.java";
if ($name =~m/^$other/){}

--SJ

Upvotes: 0

Miguel Prz
Miguel Prz

Reputation: 13792

@Shmuel answer suits your needs, but if you are looking for common way of extract the filename from a complete path name, you can use File::Basename:

use strict;
use warnings;
use File::Basename;

my ($name, $path, $suffix) = fileparse("/example/path/test.java", qw/.java/);

print "name: $name\n";  
print "path: $path\n";
print "suffix: $suffix\n";

it prints:

name: test
path: /example/path/
suffix: .java

Upvotes: 1

Shmuel Fomberg
Shmuel Fomberg

Reputation: 546

'*.java' is not a valid regex. you probably want to use this code:

my $other = '\.java$';
if ($name =~ m/$other/) {

Upvotes: 1

Related Questions