priyasony has asked for the wisdom of the Perl Monks concerning the following question:

I need a specific word in a file name and file content should be pulled out from files among directory

I m new to perl . please help me
!/usr/bin/perl -w my $directory = "/home/grds/datafiles"; opendir(DIR, $directory) or die "couldn't open $directory: $!\n"; @files = grep("EXP", readdir(DIR)); closedir(DIR); foreach $file (@files) { # print "$file\n"; open ($file }

example file name : EXPresult_3D0R0000002345_test345_cache1_IND0000ASD123_2014_04_12_18_56_12

I need 3D0R0000002345, test345, cache1, IND0000ASD123, 2014_04_12 should be stored in CSV file with separate columns.

Replies are listed 'Best First'.
Re: I want specific word to be stored in a CSV file
by Laurent_R (Canon) on Jun 20, 2015 at 11:28 UTC
    This code line is probably not doing what you think (although I am not completely sure of what you think it does) :
    @files = grep("EXP", readdir(DIR));
    In Perl, the grep function takes an array or a list of items, applies the piece of code supplied as a first argument, and returns the items for which this piece of code evaluates to true.

    If you are looking for "EXP" in the file names, then you could try to change it to:

    my @files = grep { /EXP/ } readdir(DIR);
    which would give you an array of file names matching the /EXP/ pattern.

    The second error in your code is that the readdir operator returns a list of files without the path, so that you need to prefix the file names with the $directory variable to be able to open them. Using the glob function might be easier and provide the file list, with the path, in a single step, for example you might try something like this:

    my @files = glob ("/home/grds/datafile/*EXP*.*");
    You haven't said enough for me to be able to provide more guidance at this point.

    Update: fixed a typo.

Re: I want specific word to be stored in a CSV file
by Anonymous Monk on Jun 20, 2015 at 07:39 UTC
    Here you go priyasony, just fill in the blanks, Path::Tiny, perlintro, split, Modern Perl
    #!/usr/bin/perl -- use strict; use warnings; Main( @ARGV ); exit( 0 ); sub Main { my( @dirs ) = @_; my @files = GetFiles( @dirs ); for my $file( @files ){ SnackFiles( $file ); } } sub GetFiles { ... } sub SnackFiles { my( $file ) = @_; ... split ... }