2

I have a directory where there are more than 10 files which start with pattern "my_Report". While i tried using glod for this job,it just picked only a single file . Is there any problem with the syntax below

$g_map{"Rep"} = glob ("data_1/reports/my_Report*"); 

Alternatively , i tried using grep to find all the files and stored it in a hash

$g_map{"Rep"} = [grep {!/\.xh$/} <data_1/reports/my_Report*>]; 

My Requirement is to find all the files with specific pattern from the directory and store it in a hash with key "Rep" How do i achieve the same with glob?

Thanks in Advance

3
  • In the upper command, there is a / at the beginning of the path. In the lower one, there is not. Commented Sep 15, 2016 at 11:49
  • @simbabque : Sorry that's a typo , but that isnt the issue , even without / , i get this problem, should be a problem with the way iam using glob Commented Sep 15, 2016 at 11:53
  • I was going to say add the output of ls, but mob is right below in their answer. Commented Sep 15, 2016 at 11:56

2 Answers 2

3

Your first call is in scalar context. In scalar context, glob returns (at most) a single result.

To retrieve all the matching files, use list context (like you do in your second call)

$g_map{"Rep"} = [ glob("data_1/reports/my_Report*") ] 

or if you are expecting one result or just want the first result

($g_map{"Rep"}) = glob("data_1/reports/my_Report*"); 
Sign up to request clarification or add additional context in comments.

1 Comment

I must have been typing out my answer as you were :) At least OP has a few different options now
2

glob returns a list, but you're calling it in scalar context, which is why you're only getting a single result. Try this:

@{ $g_map{Rep} } = glob ("data_1/reports/my_Report*"); 

That'll turn $g_map{Rep} hash key into an array reference, and all of the files will be stored in it.

You can access it like this:

for (@{ $g_map{Rep} }){ print "filename: $_\n"; } 

1 Comment

Note that this isn't the ordinary case of a list in scalar context. Instead, glob behaves as an iterator in scalar context, which allows loops like while ( my $node = glob 'pattern' ) { ... }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.