http://www.perlmonks.org?node_id=1050670


in reply to File Manipulation

Adding my personal “toady” to this, I view such problems in an awk-like sort of way.   There are two “kinds of” lines here:   “those that look like [servername],” and, in the simplest case, “those that don’t.”  There is one thing to be done in each case.

The data-structure of choice is a hashref, whose elements are arrayrefs containing the file-names.   Perl’s “auto-vivification” feature does, as intended, most of the work, viz:

(extemporaneous coding follows ... your syntax may vary ... stripped to the bare parts for clarity)

my $server_name; my $results; while (my $line = <$file>) { if ($line =~ /\[(.*)\]/) { $server_name = $1; } elsif ($line =~ /(\/.*)/) { die "file doesn't begin with servername line!" unless defined($server_name); push @{ $results->{$server_name} }, $1; } } foreach my $k (keys $results) { print "$k: " . join(" ", @{ $results->{$k} } ) . "\n"; }

Notice how, in the push statement, we simply rely upon Perl to create a new hash-bucket, if one does not yet exist, and to treat the whole thing as an arrayref upon which we can push things.   This is the “auto-vivification” of which I was speaking.   Notice that the program will die if it detects (and that it does look for ...) that the first line in the file is not a server-name record.   The other bits of writing things on multiple source-lines and so forth are just my personal style.