0

我编写了一个为文件添加新值的程序。文本文件。现在我想编写选项,以便我可以对所选列的文件中的数据进行排序,并能够使用正则表达式搜索任何列中的数据。怎么办?

sub show_database 
{
     $file = 'baza.txt';
     print "Database \n";
     open(my $data, '<', $file) or die "Could not open '$file' $!\n";

     while (my $line = <$data>) 
     { 
         chomp $line;
         my @fields = join(" ", split(';', $line));
         print @fields;
         print " ";
         print "\n";

     }
}
sub insert{

    print "\n \nInset new data: Name;Surname;Year \n";

    open(PLIK,'baza.txt');
    while(<PLIK>)
    {
      $linia = $_;
    }
    $ostatnia = $linia;
    @tablica = $ostatnia;
    @tab = split(/;/,$ostatnia);

    $poprzedni = $tab[0];
    $poprzedni++;

    close PLIK;

    $dane = <STDIN>;
    open(BAZA, '>>baza.txt');
    print BAZA $poprzedni;
    print BAZA ";";
    print BAZA $dane;


    close BAZA;
}
sub menu{

    print "\n \n \n \n";
    print "1 - Read database \n";
    print "2 - Insert new row \n";
    print "0 - EXIT \n \n"; 
    $opcja = <STDIN>;
}
system("clear");
menu();
if($opcja == 1)
{
    show_database();
}
if($opcja == 2)
{
    insert();
    menu();
}
if($opcja == 0)
{
    exit;
}
4

2 回答 2

1

我建议使用Tie::File

#!/usr/bin/perl
use strict;
use warnings;

use Tie::File;

tie my @file, Tie::File, "/path/to/some/file.txt" or die $!;

@file = sort by_column1 @file;
print join("\n", @file) . "\n";

untie @file;

sub by_column1 {
    (split(";", $a))[1] <=> (split(";", $b))[1]
}

另一种选择是使用DBD::CSV

于 2013-03-29T18:45:39.090 回答
0

好的,我解决了。wyszukwaniem 现在使用正则表达式处理选定列之后的文件。

于 2013-04-01T19:51:04.323 回答