Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't Perl recognize the file name?

I’m trying to do a match file name with a document with an if condition, but Perl doesn’t seems to catch it. I defined my document as:

my $file = $filename

Which $filename is equals to "/Desktop/src/file_top.sv". I’m running a program that reads the $filename and if the file is not named "file_top.sv", then the program doesn’t create the other file (name is not relevant). I’m trying to do it with an if condition like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if($filename =~ /^file\_top.*\.sv$/){
   #do something....
}

But, it doesn’t seem to work. Am I doing something wrong? Do you know any other alternatives? Should I use the whole path?

>Solution :

It does not match because ^ means "start of the string", which in your case is the / character before Desktop. Here is an approach to match just the file name without the directory path:

use warnings;
use strict;
use File::Basename qw(basename);

my $filename = "/Desktop/src/file_top.sv";

if (basename($filename) =~ /^file_top.*\.sv$/){
    print "do something....\n";
}
else {
    print "do something else....\n";
}

This will match filenames like file_top.sv and file_top123.sv, but it will not match abc_file_top.sv.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading