Oh wise monks,

I seek to increase my regular expression foo and ask for your guidance in streamlining this snippet I wrote to split up a file I have containing VirtualHost entries for Apache. In agreeing to host my friends' websites I have grown lazy and accumulated many VirtualHosts in one single file. Now is the time to clean up my act. Here's what I have which works, I ask your teachings in how to make this code more elegant.

#!/usr/bin/perl use strict; use warnings; open(FH, '< vhosts.conf'); my $content = do {local $/; <FH> }; my $start = q{<VirtualHost \*:80>}; my $finish = q{</VirtualHost>}; my @vhosts = $content =~ m!$start(.*?)$finish!sg; foreach my $vhost (@vhosts) { my ($name) = $vhost =~ /ServerName\s(\S+)/; open(OUT, "> $name.conf") or die "Can't open outfile $name: $!\n"; print OUT "<VirtualHost *:80>"; print OUT $vhost; print OUT "</VirtualHost>"; close(OUT); } 1;

For those not familiar with the data I'm trying to split up here's an example:

<VirtualHost *:80> ServerName www.foobar.com ServerAlias foobar.com DocumentRoot /var/www/foobar.com <Directory /var/www/foobar.com> Order allow,deny Allow from all </Directory> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i -> %U\" \"%{Use +r-Agent}i\ "" combined ErrorLog /var/log/apache2/foobar.com.error_log CustomLog /var/log/apache2/foobar.com.access_log combined Include conf/deflate.conf </VirtualHost>

In reply to Clean up httpd.conf virtual host mess with perl by redhotpenguin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.