0

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

4 Answers 4

1

@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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks miguel ,But here my problem i will be etting the value from database my pattern will be anything like ,.,*java so iwill be having this in variable on the fly so i need to check the pattern coming from back end and string
1

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

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

Comments

0

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

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

--SJ

Comments

0

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.