Search for specific line in array and output to an array in perl

Question!

I have an array that contains the data from a text file.

I want to filter the array and copy some information to another array. grep seems to not work.

Here's what I have

$file = 'files.txt';

open (FH, "< $file") or die "Can't open $file for read: $!";
@lines = <FH>;
close FH or die "Cannot close $file: $!";

chomp(@lines);

foreach $y (@lines){

    if ( $y =~ /(?:[^\\]*\\|^)[^\\]*$/g ) {
        print $1, pos $y, "\n";
    }
}

files.txt

public_html
Trainings and Events
General Office\Resources
General Office\Travel
General Office\Office Opperations\Contacts
General Office\Office Opperations\Coordinator Operations
public_html\Accordion\dependencies\.svn\tmp\prop-base
public_html\Accordion\dependencies\.svn\tmp\props
public_html\Accordion\dependencies\.svn\tmp\text-base

The regular expression should take the last one or two folders and put them into their own array for printing.

By : cacartano


Answers

I can't write a full answer because I'm using my phone. In any case zdim has mostly answered you. But my solution would look like this

use strict;
use warnings 'all';
use feature 'say';

use File::Spec::Functions qw/ splitdir catdir /;

my $file = 'files.txt';

open my $fh, '
By : Borodin


A regex can get very picky for this. It is far easier to split the path into components and then count off as many as you need. And there is a tool that fits your exact purpose, the core module File::Spec, as mentioned by xxfelixxx in a comment.

You can use its splitdir to break up the path, and catdir to compose one.

use warnings 'all';
use strict;
use feature 'say';

use File::Spec::Functions qw(splitdir catdir);

my $file = 'files.txt';    
open my $fh, '
By : zdim


This video can help you solving your question :)
By: admin