Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^3: Open a folder

by blue_cowdawg (Monsignor)
on Jan 08, 2013 at 14:51 UTC ( #1012248=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Open a folder
in thread Open a folder

      However I want to iterate through each text file and do some basic calculations(all in 1 sub) within each file.

Add the sub to your code thusly:

| in your while loop invoke: process_file($tmp_dir,$file); | and then after your loop sub process_file { my($path,$node)=@_; my $fname = $path . '\' . $node; open FIN,"<$fname" or die "$fname:$!"; while (my $line=<FIN>){ chomp $line; | do something here. } }


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg


Comment on Re^3: Open a folder
Download Code
Re^4: Open a folder
by Dr Manhattan (Beadle) on Jan 09, 2013 at 06:15 UTC

    Hi blue cowdawg

    I tried this:

    #!/usr/bin/perl -w use strict; use warnings; my $dir = 'C:\Users\ZB\Desktop\Text Files'; opendir (DIR, $dir) or die $!; while (my $file = readdir(DIR)) { next if $file eq '.'; next if $file eq '..'; &countWords($dir, $file); #call sub } sub countWords { my $line = @_; #receive file as input my @array = split(/ /, $line); print "$#array\n"; } closedir(DIR);

    It is the same thing as earlier, I just added a small sub which is supposed to parse each file into an array, count the words and print the output(total words). Did I call the sub correctly? And does the sub receive the file correctly? When I run the script it gives the same answer(total words) for each text file, which is incorrect.

    Thank you

          And does the sub receive the file correctly? When I run the script it gives the same answer(total words) for each text file, which is incorrect.

      Professor Cowdawg just drew a red "X" across your assignment.

      sub countWords { my $fname=join("/",@_); open FIN,"< $fname" or die "$fname:$!"; my @lines=<FIN>; chomp @lines; close FIN; my $count=0; foreach my $line(@lines){ map { $count++ } split (/[\s\t\n]+/,$line); } printf "There are %d words in %s\n",$count,$fname; }
      You are not counting anything in your sub at all. You actually have to read the file in order to count the words in it.


      Peter L. Berghold -- Unix Professional
      Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1012248]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2014-12-25 16:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (160 votes), past polls