2

我对 Perl 很陌生,对如何去做这件事不太了解。

我遇到了一些代码,它读取一个名为 .pgm 的文件,并将文件SeaWiFS_median_depth.35N.35S.180W.180E.pgm中的一些像素值重新缩放为纬度、经度和深度,并在我运行脚本时将它们打印在屏幕上。

my $depth_file = 'SeaWiFS_median_depth.35N.35S.180W.180E.pgm';

open F,$depth_file or die "Could not open $depth_file ($!)";

<F>;    # skip header line
my($wid,$hgt) = split ' ',scalar <F>;
<F>;    # skip another header line

$wid == 36000 or die "Unexpected width in depth file\n";
$hgt ==  7000 or die "Unexpected height in depth file\n";

my $inc = 360/$wid;

my $log500 = log(100/0.2);

for($lat = 35 - $inc/2; $lat > -35; $lat -= $inc){
  for($lon = -180 + $inc/2; $lon < 180; $lon += $inc){

    read(F,$pixel,1) == 1 or die "Error reading $depth_file ($!)";
    $pixel = unpack "C",$pixel;

    printf "%7.3f %8.3f ",$lat,$lon;

    if($pixel == 0){
      print "no data\n";
    }
    elsif($pixel == 1){
      print "land\n";
    }
    elsif($pixel == 255){
      print "cloud or other masking condition\n";
    }
    else{
      $depth = 0.2*exp($log500*($pixel - 2)/252);
      printf "%6.2f\n",$depth;  # depth in meters
    }
  }
}

但是,我想要做的是将屏幕上打印的值 - 纬度、经度和深度写入文本(制表符分隔)或 csv 文件,以便我可以在 R 或 GIS 软件包等其他程序中使用它来做进一步分析。

有人可以帮我吗?

4

1 回答 1

1

您可以使用“>>”运算符将脚本的输出定向到文件中。像这样使用它:perl /your/script.pl > /your/text/file.txt 如果要动态创建新文件,请使用“>>”。 perl /your/script.pl >> /your/text/file.txt

您的第二个选项是在 Perl 中打开一个文件句柄,如下所示: open my $fh, ">>", "/yout/text/file.txt" or die "Failed to open file: $!";. open在第一条语句下方添加这一行。

这将创建您要写入的文件。要将内容打印到文件中,请将文件句柄 ( $fh) 添加到print语句中,如下所示: printf $fh "%6.2f\n",$depth; # depth in meters

要操作数据的分隔符,请将\n(换行符)替换为您想要的分隔符(\t用于制表符)。

完整的 Perl 示例:

my $depth_file = 'SeaWiFS_median_depth.35N.35S.180W.180E.pgm';

open F,$depth_file or die "Could not open $depth_file ($!)";
open my $fh, ">>", "/yout/text/file.txt" or die "Failed to open file: $!";


<F>;    # skip header line

my($wid,$hgt) = split ' ',scalar <F>;

<F>;    # skip another header line

$wid == 36000 or die "Unexpected width in depth file\n";
$hgt ==  7000 or die "Unexpected height in depth file\n";

my $inc = 360/$wid;

my $log500 = log(100/0.2);

for($lat = 35 - $inc/2; $lat > -35; $lat -= $inc){
  for($lon = -180 + $inc/2; $lon < 180; $lon += $inc){

    read(F,$pixel,1) == 1 or die "Error reading $depth_file ($!)";
    $pixel = unpack "C",$pixel;

    printf "%7.3f %8.3f ",$lat,$lon;

    if($pixel == 0){
      print "no data\t";
    }
    elsif($pixel == 1){
      print "land\t";
    }
    elsif($pixel == 255){
      print "cloud or other masking condition\t";
    }
    else{
      $depth = 0.2*exp($log500*($pixel - 2)/252);
      printf $fh "%6.2f\t",$depth;  # depth in meters
    }
  }
  print $fh, "\n"; # new line after each line of the image
}
于 2015-05-19T08:26:43.820 回答