简体   繁体   English

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

[英]match variable name in reading each line of a file to create view ddl

I have an input file,我有一个输入文件,

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

I would like it read each of the line and distinguish what columns belong for TableName1 so I can build a view ddl like this: CREATE VIEW TABLENAME1 AS SELECT Column1, Column2 From TableName1;我希望它读取每一行并区分属于 TableName1 的列,这样我就可以像这样构建一个视图 ddl: CREATE VIEW TABLENAME1 AS SELECT Column1, Column2 From TableName1; and Next will be View TableName2 etc.接下来是 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);
}

I'd do it something like this.我会做这样的事情。

Parse the data into a data structure.将数据解析为数据结构。 I'm using an array of anonymous arrays.我正在使用一组匿名 arrays。 In the anonymous arrays, the first element is the table name and any other elements are columns.在匿名 arrays 中,第一个元素是表名,其他元素是列。

#!/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;
}

And then walk the data structure to do whatever you want with the data (here, I'm just displaying it).然后遍历数据结构,对数据做任何你想做的事情(这里,我只是展示它)。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM