0

好吧,这个想法是删除文件的描述方向并将其存储在哈希中

这是文件 /home/opmeitle/files-pl/bookmarks2 中的内容

    }, {
       "date_added": "12989744094664781",
       "id": "1721",
       "name": "Perl DBI - dbi.perl.org",
       "type": "url",
       "url": "http://dbi.perl.org/"
    }, {
       "date_added": "12989744373130384",
       "id": "1722",
       "name": "DBD::mysql - MySQL driver for the Perl5 Database Interface (DBI) - metacpan.org",
       "type": "url",
       "url": "https://metacpan.org/module/DBD::mysql"
    }, {

现在,perl 中的代码。

use strict;

open(FILE, '/home/opmeitle/files-pl/bookmarks2');  
my @lines = <FILE>;
my @list55;
my $count = 1;
my $n = 0;
my %hash=();   #$hash{$lines[$n]}=$lines[$n];
    while ($lines[$n]) {
        if ($lines[$n] =~ /(http:|https:|name)/) {
            if ($lines[$n] =~ s/("|: |,|id|url|name|\n)//g) {
                if ($lines[$n] =~ s/^\s+//){
                    if ($lines[$n] =~ /http:|https/){ 
                        $hash{$lines[$n]} = '';
                    }
                    else {
                        $hash{$n} = $lines[$n];
                    }
                }
            }
        }
    $n++;
    $count++;
    }
close(FILE);
# print hash
my $key;
my $value;
while( ($key,$value) = each %hash){
    print "$key = $value\n";
}

执行脚本后的结果。

http://dbi.perl.org/ = 
https://metacpan.org/module/DBD::mysql = 
3 = Perl DBI - dbi.perl.org
9 = DBD::mysql - MySQL driver for the Perl5 Database Interface (DBI) - metacpan.org

但我需要这样的东西

http://dbi.perl.org/ = Perl DBI - dbi.perl.org
Perl DBI - dbi.perl.org = DBD::mysql - MySQL driver for the Perl5 Database Interface (DBI) - metacpan.org

谢谢你的回答。

4

2 回答 2

2

正如@amon 所暗示的,Chrome 书签是 JSON 格式,在CPAN上有几个很好的模块。

use strict;
use warnings;
use JSON;

my $file = '/home/opmeitle/files-pl/bookmarks2';
open my $fh, '<', $file or die "$file: $!\n";
my $inhash = decode_json(join '', <$fh>);
close $fh;

my %outhash = map traverse($_), values %{ $inhash->{roots} };
sub traverse
{
  my $hashref = shift;

  if (exists $hashref->{children}) {
    return map traverse($_), @{ $hashref->{children} };
  } else {
    return $hashref->{url} => $hashref->{name};
  }
}

现在%outhash有了你想要的数据。

编辑:帮助了解这里发生了什么:

use Data::Dumper;
print Dumper($inhash); # pretty-print the structure returned by decode_json
于 2012-09-02T19:56:28.140 回答
1

正如其他人所说,最好的办法是将 JSON 数据加载到 Perl 数据结构中。使用该JSON模块很容易做到这一点。在我们这样做之前,我们需要读入文件。有两种方法可以做到这一点。非 CPAN 方式:

# always ...
use strict;
use warnings;

my $file = '/home/opmeitle/files-pl/bookmarks2';

my $text = do {
  open my $fh, '<', $file or die "Cannot open $file: $!\n";
  local $/; #enable slurp
  <$fh>;
};

或 CPAN 方式

# always ...
use strict;
use warnings;

use File::Slurp;
my $text = read_file $file;

一旦你读入文件,然后解码

use JSON;

my $data = decode_json $text;

Please post a whole file and a better description of what you want and I would be glad to comment on a more formal way of traversing the datastructure.

于 2012-09-02T20:52:19.013 回答