G'day x-lours,
You seem very impressed with 'parse the file in "oneline"'.
It is not impressive at all.
It's exceptionally difficult to read, a maintenance nightmare, and extremely error-prone.
I strongly recommend you avoid code like this.
You said you wanted to use the result in 'the rest of the script';
for that, you'd want to put the code in a subroutine; possibly in a module for reuse in other scripts.
Below, I present a technique for getting the exact result you want:
it's a standalone solution which you can adapt for a subroutine or module;
it is very straightforward code that's easy to read and maintain;
it has a basic sanity check and reports I/O errors.
Here's pm_11142528_parse_file.pl:
#!/usr/bin/env perl
use strict;
use warnings;
use autodie;
die "Usage: $0 input_file\n" unless @ARGV;
my $in_file = $ARGV[0];
my $result = [];
my $block_start = 'objet => debut';
my $block_end = 'objet => fin',
my $rec_skip = '...';
{
open my $fh, '<', $in_file;
while (<$fh>) {
chomp;
next if $_ eq $rec_skip or $_ eq $block_end;
if ($_ eq $block_start) {
push @$result, {};
next;
}
my ($key, $value) = split /\s*=>\s*/;
$value =~ s/^"?(.*?)"?$/$1/;
$result->[-1]{$key} = $value;
}
}
use Data::Dump;
dd $result;
Sanity check:
$ ./pm_11142528_parse_file.pl
Usage: ./pm_11142528_parse_file.pl input_file
I/O exception handling:
$ ./pm_11142528_parse_file.pl not_a_file
Can't open 'not_a_file' for reading: 'No such file or directory' at ./
+pm_11142528_parse_file.pl line 17
Here's the input data you provided:
$ cat pm_11142528_parse_file.txt
objet => debut
index => 1
a => "premiere valeur"
...
z => "dernier mot"
objet => fin
...
objet => debut
index => 77
a => "autre valeur"
...
z => "aurai-je le dernier mot ?"
objet => fin
A sample run with expected results:
$ ./pm_11142528_parse_file.pl pm_11142528_parse_file.txt
[
{ a => "premiere valeur", index => 1, z => "dernier mot" },
{ a => "autre valeur", index => 77, z => "aurai-je le dernier mot ?"
+ },
]
'could you help me to proove him Perl is as efficient as Ruby ? (even if it is not a "oneline")'
It is a common misconception that it is somehow more efficient
to write single lines of code that are hundreds of characters long.
Writing code without whitespace is also not more efficient; itjustreducesthereadabilityofthecode.
Use Benchmark to measure the efficiency of your Perl code.
I imagine Ruby has something similar which you could use for a comparison (but I've no idea what that might be).
|