Perl | Accessing a Directory using File Globbing

In Perl, a directory is used to store values in the form of lists. A directory is quite similar to a file. Just like a file, the directory also allows performing several operations on it. These operations are used for the modification of an existing directory or creation of a new one. A directory can be very easily opened and processed using the built-in function glob.

Glob:
It returns a list of files that match the expression passed in the argument. This function can print all or the specific files whose extension has been passed to it.

Syntax:



@list = <*>; // Prints all files in current directory
@list = glob(“*.pl”); // Prints all files in current directory with extension .pl
@list = glob(‘//GeeksforGeeks//Files//*); // Prints all files in the given path

Here are some examples that illustrate accessing a directory using File Globbing.
Examples:

  • Accessing the current directory of the script:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #!/usr/bin/perl -w
      
    # Accessing files using glob function
    @files = glob('*');      # Returns list of all files
    foreach $file (@files)   # Loop to run through all files
    {
        print $file . "\n";     # Print all files

    chevron_right

    
    

    Output:
    Glob Output1

  • Opening a specified directory:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #!/usr/bin/perl -w
      
    # Prints only the filename excluding the path
    use File::Basename; 
      
    # Returns list of all files
    @files = glob('C:/Users/GeeksForGeeks/Folder/*'); 
    foreach $file (@files) # Loop to run through all files
    {
        print basename($file), "\n"; # Print all files

    chevron_right

    
    

    Output:



  • My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.