467,171 Members | 1,263 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,171 developers. It's quick & easy.

opening file using wild card

Looking2Learn
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
  • viewed: 6148
Share:
3 Replies
nithinpes
Expert 256MB
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 256MB
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
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.

Similar topics

reply views Thread by Gerry Viator | last post: by
1 post views Thread by MFRASER | last post: by
1 post views Thread by =?Utf-8?B?S3Jpc3RpbmUgdGhlIERyYWdvbkxhZHk=?= | last post: by
8 posts views Thread by hiro | last post: by
reply views Thread by jmelasic1@loyola.edu | last post: by
7 posts views Thread by W. eWatson | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.