Home: Need a Custom or Prewritten Perl Program?: I need a program that...:
Perl Directory Tree Program



perlbegginer02
New User

Nov 29, 2013, 12:47 PM


Views: 15269
Perl Directory Tree Program

Hello everyone, I'm new to writing perl scripts and I need help with a program assignment.

The assignment is to Develop a program to analyze the directory structure of a Linux disk and identify any files larger that 500kbytes. But I need to use a for each loop and sub routine within the program.

I have only gotten up to this but, I'm not sure if its the right direction or not.


Code
#!/usr/bin/perl 
use warnings;

my $directory = '/home';

opendir (DIRFH, $directory) or die "Can't open directory! $! \n";

my @direct = $directory;

for each
$directory (@direct)
{
if (-d $file) {
print "This is a directory: " . $file;
}




(This post was edited by perlbegginer02 on Nov 29, 2013, 12:49 PM)


BillKSmith
Veteran

Nov 30, 2013, 8:04 AM


Views: 15227
Re: [perlbegginer02] Perl Directory Tree Program

There are many ways to do this assignment. You have a start on one of them. Add 'use strict;' and fix all the problems that perl tells you about. Then ask for help again.
Good Luck,
Bill


Zhris
Enthusiast

Dec 1, 2013, 2:12 AM


Views: 15184
Re: [perlbegginer02] Perl Directory Tree Program

An approach which is out of scope of your assignment, but nonetheless shows a proper way to perform this task, which you can study later:


Code
#!/usr/bin/perl 
use strict;
use warnings;
use Cwd;
use File::Find;
use File::stat;
use Data::Dumper;

my $min_kb = 500;
my @output;
find( sub { push @output, $File::Find::name if (stat($File::Find::name)->size / 1024 >= $min_kb) }, getcwd );
print Dumper \@output;


Chris


(This post was edited by Zhris on Dec 1, 2013, 2:17 AM)


Zhris
Enthusiast

Dec 1, 2013, 2:24 AM


Views: 15178
Re: [perlbegginer02] Perl Directory Tree Program

With regards to your assignment, although syntaxly incorrect, you are correctly using a foreach loop to attempt to transverse through each file of the directory. For the subroutine, you will likely need one for recursion IF you need to process child directories. You would also probably use a subroutine which takes a filepath, calculates the filesize in kb, and possibly push the filepath onto your output array if it exceeds 500.

Chris