LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [perl] array of files: remove specific ext (https://www.linuxquestions.org/questions/programming-9/%5Bperl%5D-array-of-files-remove-specific-ext-921574/)

Angel2953 01-02-2012 02:46 AM

[perl] array of files: remove specific ext
 
Hello,

I have a problem cause i have an array of files and dirs:
Code:

my @files = (
    "/path/to/file/file_1.ext1",
    "/path/to/file/file_2.ext1",
    "/path/to/file/file_3.ext1",
    "/path/to/file/file_4.ext2",
    "/path/to/dir1",
    "/path/to/file/file_5.ext2",
    "/path/to/file/file_6.ext1",
    "/path/to/dir2",
    "/path/to/file/file_7.ext3",
    "/path/to/dir3",
    "/path/to/file/file_8.ext4",
    "/path/to/file/file_9.ext5"
    "/path/to/dir4",
);

first what i need is to remove all items that are dirs and then group rest of the files into their own arrays. So i though about function that takes 2 params: 1. array to scan, 2. ext to filter and returns filtered array... And now how to implement that. I mean how to iterate throught array and remove some elements based on a filer...

perfect_circle 01-02-2012 06:29 AM

you can easily iterate over the array and create a new array that only hosts the files like this:

Code:

foreach $file (@files) {
        if ( -f $file ) {
                push(@no_dirs, $file);
        }
}

The new @no_dirs array will not contain any directory.

Cedrik 01-02-2012 06:51 PM

You can also use grep perl function to select files with specific extension, like:

Code:

my @files = (
    "/path/to/file/file_1.ext1",
    "/path/to/file/file_2.ext1",
    "/path/to/file/file_3.ext1",
    "/path/to/file/file_4.ext2",
    "/path/to/dir1",
    "/path/to/file/file_5.ext2",
    "/path/to/file/file_6.ext1",
    "/path/to/dir2",
    "/path/to/file/file_7.ext3",
    "/path/to/dir3",
    "/path/to/file/file_8.ext4",
    "/path/to/file/file_9.ext5",
    "/path/to/dir4",
);

# put all files with .ext1 extension in @ext1 array
my @ext1 = grep {/\.ext1$/} @files;

# see the result
print "$_\n" for @ext1;

# or remove all files with .ext1 extension
my @noext1 = grep {! /\.ext1$/} @files;

# see the result
print "$_\n" for @noext1;

# You can also use grep to remove dirs from list
my @just_files = grep { -f } @files;

# see result
print "$_\n" for @just_files;

# you can also combine more grep...
my @ext1_files = grep { /\.ext1$/ } grep { -f } @files;

# or simply:
my @ext1_files = grep { -f and /\.ext1$/ } @files;

# result should look like the same as with just greping .ext1 extension
# but the files existence is tested
print "$_\n" for @ext1_files;



All times are GMT -5. The time now is 11:51 PM.