Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: File Manipulation

by sundialsvc4 (Monsignor)
on Aug 23, 2013 at 13:12 UTC ( #1050670=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: File Manipulation
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1050670]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (10)
As of 2014-08-22 11:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (155 votes), past polls