Login or Sign up Help | Site Map
Connecting Tech Pros Worldwide

opening file using wild card

Question posted by: Looking2Learn (Newbie) on July 3rd, 2008 01:29 PM
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?

Code: ( text )
  1. #!usr/bin/perl
  2.  
  3. open (FILE, "***_user.txt") or die "Can't find file!" ;
  4.     print "Found file!" ;
  5. close (FILE) ;
Would you like to answer this question?
Sign up for a free account, or Login (if you're already a member).
nithinpes's Avatar
nithinpes
Expert
253 Posts
July 3rd, 2008
02:56 PM
#2

Re: opening file using wild card
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:

Code: ( text )
  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. }

Last edited by nithinpes : July 3rd, 2008 at 02:58 PM. Reason: added comment
Reply
nithinpes's Avatar
nithinpes
Expert
253 Posts
July 3rd, 2008
03:00 PM
#3

Re: opening file using wild card
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.

Reply
Looking2Learn's Avatar
Looking2Learn
Newbie
5 Posts
July 3rd, 2008
03:15 PM
#4

Re: opening file using wild card
Great, thanks!

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

Code: ( text )
  1. while(my $filename=readdir(DIR)){
  2. my file = $filename if($filename=~/^\d\d\d_user\.txt$/);
  3. }

Reply
Reply
Not the answer you were looking for? Post your question . . .
182,537 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

Top Perl Forum Contributors