On 05/03/2012 18:34, Lancashire, Pete wrote:
> my brain this morning is blocked on this one
> 
> I have a file something like
> 
> cpu01  value value value
> cpu02  value value value
> cpu03  value value value
> ...
> cpu01  value value value
> cpu02  value value value
> cpu03  value value value
> ...
> cpu01  value value value
> cpu02  value value value
> cpu03  value value value
> ...
> 
> in this example column 1 can be cpu\d+ and cpu_all other it can be even eth0, 
> fcs0 etc
> 
> I want to open files for writing, one for each unique value in the first 
> column,
> so that if the value of the data in the first column is "cpu01" then
> write to the file with the FH in the variable $cpu01 or if the value is 
> "cpu_all" write to the
> file with the FH assigned to the the vaule $cpu_all
> 
> This has to be simple ...

Hi Pete.

What you describe is possible, but setting up all those $cpu01, $cpu_all
etc. before you read the file would be awkward. Unless your environment
is more complex than you describe I suggest a hash of file handles. The
program below gives an example using your data.

HTH,

Rob


use strict;
use warnings;

my %fh;

while (<DATA>) {

  my ($class) = /^(\w+)/;
  next unless $class;
  
  unless ($fh{$class}) {
    my $file = "$class.data";
    open $fh{$class}, '>', $file or die "Unable to open $file for output: $!";
  }
  
  select $fh{$class};
  print;
}

__DATA__
cpu01  value value value
cpu02  value value value
cpu03  value value value
...
cpu01  value value value
cpu02  value value value
cpu03  value value value
...
cpu01  value value value
cpu02  value value value
cpu03  value value value
...

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to