By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,811 Members | 1,978 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,811 IT Pros & Developers. It's quick & easy.

opening file using wild card

Looking2Learn
P: 5
Hey,
I'm trying to open a txt file, but I won't know the first three characters of the filename. For example, I want to open a "user.txt" file, and I know it will have three digits in front of it, like "123_user.txt", but they could be any three digits. Is there a way to introduce a wild card into the open command to specify this?

Expand|Select|Wrap|Line Numbers
  1. #!usr/bin/perl
  2.  
  3. open (FILE, "***_user.txt") or die "Can't find file!" ;
  4.     print "Found file!" ;
  5. close (FILE) ;
  6.  
Jul 3 '08 #1
Share this Question
Share on Google+
3 Replies


nithinpes
Expert 100+
P: 410
Wildcard cannot be used with open function. Are you trying to open any file/all files in the current directory that matches your criteria?
I am assuming that you want to search for files that match the criteria and open them. In this case, you can parse through the directory and fetch all files that match the criteria and open them for reading as below:

Expand|Select|Wrap|Line Numbers
  1. #!usr/bin/perl
  2. use strict;
  3.  
  4. my @files;
  5. opendir(DIR,".") or die "opening directory failed:$!";  # '.' for pwd.Use dir path if required. 
  6. while(my $filename=readdir(DIR)){
  7.  push @files,$filename if($filename=~/^\d\d\d_user\.txt$/);
  8. }
  9. closedir(DIR);
  10. foreach my $file (@files) {
  11. print "found $file\n";
  12. open (FILE, "$file") or die "Can't find $file!" ;
  13. while(<FILE>) {
  14. ### read
  15. }
  16. close (FILE) ;
  17. }
  18.  
Jul 3 '08 #2

nithinpes
Expert 100+
P: 410
In case you want to open any single file that match the criteria assign $filename to $file when a match is found and quit the while(my $filename=readdir(DIR)) {} loop.
Jul 3 '08 #3

Looking2Learn
P: 5
Great, thanks!

And yes, there will only be one matching file. So, I'll use:

Expand|Select|Wrap|Line Numbers
  1. while(my $filename=readdir(DIR)){
  2. my file = $filename if($filename=~/^\d\d\d_user\.txt$/);
  3. }
  4.  
Jul 3 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.