LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   stuck on perl script (https://www.linuxquestions.org/questions/programming-9/stuck-on-perl-script-610384/)

farkus888 01-01-2008 12:46 PM

stuck on perl script
 
first off, the broken code;

Code:

#!/usr/bin/perl

#pragmas
use strict;

#modules
use File::Find ();

#declaring global variables
use vars qw/@filenames/;

@filenames = (File::Find::find(\&getfiles, "/some/dir/here"));

foreach (@filenames) {
        print "$_\n";
}

sub getfiles {
        if (/part_of_filename/ && (int(-M) < 1)) {
                unshift @filenames, $File::Find::name;
        }
        chomp(@filenames);
        return @filenames;
}

I want this to print each absolute filename that matches the if test in my getfiles subroutine but it just prints a blank line and ends. I do realize that

Code:

sub getfiles {
        if (/part_of_filename/ && (int(-M) < 1)) {
                print "$File::Find::name\n";
        }
}

does what I am asking for. I intend to do much more with that list of filenames later, but I haven't written the rest because this part doesn't work yet.

rikxik 01-02-2008 03:09 AM

Sample files:

Code:

$ ls -ltr |tail
-rw-r-----  1 sdass    informix    274 Dec 26 04:27 data.trimmed
-rw-r-----  1 sdass    informix      35 Dec 26 06:51 userlist
-rwxr-xr-x  1 sdass    informix    199 Dec 26 08:16 conv.sh
-rw-r-----  1 sdass    informix    112 Dec 26 08:20 passwdlist
-rwxr-x---  1 sdass    informix    146 Dec 26 08:24 conve.sh
-rwxr-xr-x  1 sdass    informix    266 Dec 26 10:09 loop.sh
-rw-r-----  1 sdass    informix      23 Dec 27 02:22 pinfile
-rw-r-----  1 sdass    informix      0 Jan  2 08:53 abcd
-rw-r-----  1 sdass    informix      63 Jan  2 09:02 abc.txt
-rwxr-xr-x  1 sdass    informix    300 Jan  2 09:06 fnd.pl

Run this:
Code:

$ cat fnd.pl
#!/usr/bin/perl

#pragmas
use strict;

#modules
use File::Find;

#declaring global variables
use vars qw/@filenames $str $dir/;

$str = 'abc';
$dir = $ENV{'PWD'};

find(\&getfiles, $dir);
print "$_\n" foreach @filenames;

sub getfiles {
        if (/$str/ && (int(-M) < 1)) {
                unshift @filenames, $_;
        }
}

Output:

Code:

$ fnd.pl
abcd
abc.txt

Run diff on your code with the one pasted above to see the difference.

HTH

farkus888 01-02-2008 08:37 AM

I had actually figured this out on my own last night but hadn't gotten around to noting it here yet. the real thing that was breaking it was that I was trying to assign the output of my call to File::Find back to the @filenames array, which can be skipped because its being used as a global variable. thank you, that would have enlightened me if I had still been in the dark.


All times are GMT -5. The time now is 03:14 PM.