We help IT Professionals succeed at work.

Assistance understanding this script

Simon336697
Simon336697 asked
on
Hi guys!

Im having problems trying to understand what the following code snippet does.
Any help appreciated.

What i do understand is....

- Open a directory called c:\started
- For each file $f in the started folder, read the file, and thats where i fall down.

=============================================================

opendir(DIR,"c:\\started");
foreach $f (readdir(DIR)) {
$file = $f;
$file =~ s/.*\///;
open(SUB,"<started/$f");
while (<SUB>) {
$_ = lc($_);
$_ =~ s/
//g;

$line = $_;
if ($_ =~ /^\n$/) { next; }

chomp($_);


print $f;
}
}

==========================================================
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
opendir(DIR,"c:\\started"); #Open a directory called c:\started
foreach $f (readdir(DIR)) { #- For each file $f in the started folder,
$file = $f;
$file =~ s/.*\///;
open(SUB,"<started/$f");
while (<SUB>) { #read the file
$_ = lc($_); # get a lower case version of the line , see perldoc -f lc
$_ =~ s/
//g;  # remove newlines, see perldoc perlop

$line = $_; #make a copy of the line that never seems to be used
if ($_ =~ /^\n$/) { next; } # skip lines  that still contain only a newline

chomp($_); # remove a trailing newline, see perldoc -f chomp


print $f;  #print the name of the file, see perldoc -f print
}
}

Author

Commented:
ozo youre a champion.
Really appreciate your kind help.
I have another one id like to get help on so Ill post it :>)
Im actually going through a huge script and testing things as I go, and anything im not sure about, im posting snippets :>)
CERTIFIED EXPERT
Top Expert 2007

Commented:
That code makes no sense.  If you remove all the redudant lines you are left with:
opendir(DIR,"c:\\started");
foreach $f (readdir(DIR)) {
  open(SUB,"<started/$f");
  while (<SUB>) {
    chomp;
    print $f;
  }
}

Open in new window

ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
and given that $_ is not used, you can remove the chomp too
If $file and $line are used later, it also has the side effect of setting $file to the last file, and $line to the last line in the last file
If $/ has been set, or if there are blank characters that we don't see in the s/// then it could be possible for the print of the filename to be skipped some times

Explore More ContentExplore courses, solutions, and other research materials related to this topic.