dataminer123
dataminer123

Reputation: 65

foreach loop through an array that has directory paths and filenames(perl)

1440665    8 drwxrwx---   2 smithjoe   smithjoe      1024 May 29 09:01 .
1960596    8 -rwxrwx--x   1 smithjoe   smithjoe      3190 May 29 09:00 ./file1.prl
3197096    8 -rw-rw----   1 smithjoe   smithjoe      1594 May 24 16:11 .dir/documents/file2.prl~
1790401    8 -rw-------   1 smithjoe   smithjoe      3205 May 29 09:01 .dir/files/file3.prl
6754401    8 -rw-------   1 smithjoe   smithjoe      3205 May 29 09:01 .smithjoe/file3.prl
2737401    8 -rw-------   1 smithjoe   smithjoe      3205 May 29 09:01 .smithjoe/folder2

I have an array(@file_path) with the data presented above. i want to be able to extract the file/dir name out of the array(it's the last element on the line). I have to use foreach loop. once i do that. I skip the directories and save them in a new array. i append that array with the push command.

help me out. please.

Upvotes: 0

Views: 626

Answers (2)

James Green
James Green

Reputation: 1753

I'd re-iterate @mpapec's comment, that you probably want to first approach this by fixing the data you get in, rather than trying to manipulate it. Also, I need to prefix this by saying that this WILL choke on whitespace inside filenames and paths -- and I'm not sure there's a good, reliable way to avoid that which doesn't introduce other quirks, hence the recommendation to fix up the data before you try to process it.

But, if you're stuck with the data you have, and you're confident you won't have whitespace in filenames/paths:

my @paths;
foreach my $line (@file_path) {
    my @parts = split /\s+/, $line;
    push @paths, $parts[-1];
}

...should get you on your way.

Upvotes: 2

Dave Sherohman
Dave Sherohman

Reputation: 46187

A couple hints for you:

  • Assuming that the file paths will never contain spaces, you can use the split command to separate the fields on each line and assign them to an array. If they can contain spaces, split takes an optional third parameter for the maximum number of fields to return.

  • In Perl, $array[-1] returns the last item in @array.

Those two tips should allow you to get the file path from each line.

Upvotes: 2

Related Questions