数据分析

检测系统某一目录下是否存在文件a.txt,有的话,则mv成新的文件,没有,则创建它,并向文件中输入以下数字:

1       0       1
2       1       1
3       0       1 
4       1       1 
5       0       1 
6       1       1 
7       0       1 
8       1       1

 

面试中,对这个题目产生了歧义,一时紧张,竟然不知从何下手。回来仔细一想,so easy!

1)出题者的本意解法

#!/bin/env perl  
use strict; 

if (-e 'a.txt') {   
 system "mv a.txt a.txt.old"; 
 }
  else {    
  system "touch a.txt"; }  
  
  open my $file,'>>','a.txt' or die "$!\n";  
  for(my $i=1;$i<9;$i++){   
     if ($i % 2) {      
        print $file "$i\t0\t1\n";     }    
         else {         
         print $file "$i\t1\t1\n";   
           } 
}

2)产生歧义的解法

#!/bin/env perl  
use strict;  

if (-e 'a.txt') {   
    system "mv a.txt a.txt.old"; 
}
 else {    system "touch a.txt"; 
 }  
 
 open my $file,'>>','a.txt' or die "$!\n"; 
 
  print $file <<'EOF'; 
  1       0       1 
  2       1       1 
  3       0       1 
  4       1       1 
  5       0       1 
  6       1       1 
  7       0       1 
  8       1       1 
  EOF  
  
  close $file;