Search code examples
perlconstantsglob

Can I use a Perl constant in the glob operator?


I'm parsing XML files with something like:

while (<files/*.xml>) { ... }

I want to use a constant to 'files', say

use constant FILES_PATH => 'files';
while (<FILES_PATH/*.xml>) { ... }

I hope you understand the idea, and can help me :)..

Thank you in advance.


Solution

  • Hmm, this is one reason to use Readonly instead of constant. You may be able to use & the start or () at the end of the constant to get Perl to realize it is subroutine. Let me check.

    Nope, but you can use the classic trick of creating an arrayref to dereference:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use constant DIR => "/tmp";
    
    print map { "$_\n" } <${[DIR]}[0]/*>;
    

    But since glob "*" is the same as <*> you may prefer:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use constant DIR => "/tmp";
    
    print map { "$_\n" } glob DIR . "/*";
    

    I would probably say

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Readonly;
    
    Readonly my $DIR => "/tmp";
    
    print map { "$_\n" } <$DIR/*>;