regex - Search for string in filename Perl -


i trying find filename contains string requested. instance, have string companyabc , looking search directory string in file name. want return file looking for.

i tried following using regex not string checks letters in order not looking for:

$foundfile = grep(/[comapnyabc]/i, readdir dir); 

is there way search string within file in perl , return file name?

you close, had couple of problems.

firstly, square brackets changing meaning of regex. pair of square brackets defines "character class" - set of characters match. regex match if finds one of characters. looking 'c' or 'o' or 'm' ... etc. that's not want. lose brackets.

$foundfile = grep(/comapnyabc/i, readdir dir); 

but still doesn't give quite want. instead of returning filename, you'll number of matches found. if read the documentation grep, you'll see says:

evaluates block or expr each element of list (locally setting $_ each element) , returns list value consisting of elements expression evaluated true. in scalar context, returns number of times expression true.

you assigning result of calling grep scalar variable. means calling in scalar context, why number of matches back. actual matches, need call in list context. can in couple of ways. simplest assign result array.

@foundfiles = grep(/comapnyabc/i, readdir dir); 

the array @foundfiles contain of filenames match regex. sounds expect 1 filename match. can instead:

($foundfile) = grep(/comapnyabc/i, readdir dir); 

the difference here parentheses around $foundfile. in perl presence or absence of parentheses make no difference, here make important difference. make assignment list assignment, means grep called in list context , therefore (as documentation says) returns actual matches, not count.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -