Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: File Manipulation

by sundialsvc4 (Abbot)
on Aug 23, 2013 at 13:12 UTC ( [id://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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (1)
As of 2024-04-19 00:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found