[plug] A question for perl hackers

Brian Tombleson brian at paradigmit.com.au
Thu Aug 22 00:25:16 WST 2002


> I am trying to grab the filesize in bytes from a listing like:
>    310272 Aug 21 22:18 inbox
>   5193576 Jul  7 09:45 lyndon
>         0 Aug 12 09:58 mailing lists
>     32720 Jun 10 20:10 mchoice
>     46513 Aug 16 16:18 netvigator
>         0 Aug 21 20:04 outbox
>  10069208 Aug 21 20:04 sent-mail
>   2377093 Aug 21 19:33 trash
>
> As I step through an array with foreach I would like to assign the
filesize
> in bytes (the first number) to a variable.  I need to match:

Well, checking your assumptions you can make that pretty easy ..
Assumptions:
  Format is always consistent : _X_M_D_T_F*
      where: _ is any amount of white space
            X is a number
            M is the month
            D is the day
            T is the time (or year)
            F* is the filename (allowing for spaces and other characters in
the filename).

You could do something like this ..

my @temparr = ();
my $size = 0;
my $filename = "";
foreach $line (@array) {
  @temparr = split(/\s+/,$line,5);
  $size = $temparr[0];
  $filename = $temparr[4];
  print "File ($filename) is of size: $size\n";
}

You could reduce the code much smaller.  Eg.
  my $i,$j,$k;
  foreach $i (@array) {
    ($i,$j,$j,$j,$k) = split($i,5);
    print "File ($k) is of size: $i\n";
  }

.. Or read from standard input instead ..
  my $i,$j,$k;
  while (<>) {
    ($i,$j,$j,$j,$k) = split(5);
    print "File ($k) is of size: $i\n";
  }

If you ONLY want the number ..
  foreach my $i (@array) {
    $i = shift(split($i,5));  # $i contains the file size
  }
If you ONLY want the file name ..
  foreach my $i (@array) {
    $i = pop(split($i,5));  # $i contains the file name
  }
If you ONLY want the Month ..
  foreach my $i (@array) {
    $i = split($i,5)[1];  # $i contains the month
  }

.. but I'd recommend setting out code so it's readable and maintainable
(especially when you're learning).
The aim is not to win at Perl Golf.

HTH.
Brian.




More information about the plug mailing list