在读取文件的每一行时匹配变量名称以创建视图ddl

问题描述

我有一个输入文件

                  TableName1.Column1
                  TableName1.Column2 
                  TableName2.Column1
                  TableName2.Column2
                  TableName3.Column3 etc

我希望它读取每一行并区分TableName1属于哪些列,因此我可以像这样构建视图ddl:CREATE VIEW TABLENAME1 AS SELECT Column1,Column2 From TableName1;接下来是View TableName2等。

my $file = "summary.csv";
open (my $FH,'<',$file) or die "Can't open '$file' for read: $!";
my @lines;
while (my $line = <$FH>) {
  push (@lines,$line);
}
close $FH or die "Cannot close $file: $!";

my $ln=@lines;


for (my $x=0; $x<$ln; $x++){
  print("---Start->\n") if($x == 0);
  print "---------------->\n";
  my $first = (split /\./,$lines[$x] )[0];
  my $second = $first;

  print "Second is: $second \n";


  if ((split /\./,$lines[$x] )[0]  eq $first )
  {
    print "Same Table: $lines[$x]";

  }
  else 

  {
    print "Next Table: $lines[$x]";

  }

  print("---End-->\n") if($x == $ln -1);
}

解决方法

我会做这样的事情。

将数据解析为数据结构。我正在使用匿名数组的数组。在匿名数组中,第一个元素是表名,其他任何元素是列。

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my @tables;

my $curr_table = '';

# Note: I used a DATA filehandle to test this. You'll need to
# insert your file-opening code here.

while (<DATA>) {
  chomp;
  my ($table,$column) = split /\./;

  if ($table ne $curr_table) {
    push @tables,[ $table ];
    $curr_table = $table;
  }
  push @{ $tables[-1] },$column;
}

然后遍历数据结构以对数据进行任何操作(在这里,我只是显示它)。

for my $t (@tables) {
  my ($table,@columns) = @{ $t };

  say "Table: table";
  say " * $_" for @columns;
}