I'm trying to do the first exercise in the Intermediate Perl book. It calls for taking filenames from the command line and parsing them with grep to determine which are less then 1000 bytes and then doing some transformation on the strings with map. For now I'm ignoring the "from the command line" part and just reading the files in from a directory.

I haven't reached the map part yet because I'm hung up on the grep. This is the code I have:
#!/usr/bin/perl use warnings; use strict; my $dh, $dir = "/home/msnyder/bin/etc_copy/"; my $dh; opendir($dh, $dir) or die "Unable to open directory $dir: $!."; my @files = grep -s $_ < 1000, readdir($dh); foreach (@files) { print $_ . "\n"; }

I don't think it is actually getting the size of each file because I'm getting Use of uninitialized value $_ in numeric lt (<) at ./int_perl1-1.pl line 10.

Initially, I was seeing the same error that bluethundr was getting in another thread about the filename containing a newline. I applied the substitute fix that was suggested but it didn't solve the issue. To be honest, I'm not seeing that anymore so I don't know what was causing it. I'm only seeing the error pointed out above.

After a long list of identical errors it then prints out the file names.

I've tried substituting the grep and subsequent foreach loop with a foreach loop on the directory handle:

foreach (readdir($dh)) { my $filesize = -s $_; print $_ . " " . $filesize . "\n"; }

But that just gives me Use of uninitialized value $filesize in concatenation (.) or string at ./int_perl1-1.pl line 19. outputting it before each filename is printed.

I'm not sure what other information I should be providing. If I'm missing something that will be helpful let me know.


In reply to filesize not returned? by theillien1

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.