Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Thomas Beutel http://www.beutelevision.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS 

Create an RFC822 compliant date in Perl

use Date::Manip qw(ParseDate UnixDate);

# Create an RFC822 compliant date (current time)
my $rfc822_format = "%a, %d %b %Y %H:%M %Z";
my $today         = ParseDate("Now");

my $rfc822_date   = UnixDate($today,$rfc822_format);

Cheap XML append in Perl

Here is a really cheap way in Perl to append an XML fragment to an existing XML doc. It appends it just before the last closing tag. Note that there is no validation or well-formedness checking. Use at your own risk. That said, it can be handy if you know that your XML is going to be OK.

#!/usr/bin/perl

sub xappend(\$$) { ${$_[0]} =~ s/(<\/[^>]+>\s*)$/$_[1]$1/s }

$a = "<doc><item>foo</item></doc>";
xappend($a,"<item>bar</item>");

print $a; # prints <doc><item>foo</item><item>bar</item></doc>

Easy Substitution Oneliner

Suppose you have a bunch of files where you need to make the same substitution. This oneliner will make the substitution and keep the old version in backups. This is particularly handy for configuration files.

perl -p -i.bak -e 's:oldtext:newtext:g' *.conf

From database records to XML

Here is a quick way to convert database records to XML using XML::Simple.

#!/usr/bin/perl

use warnings;
use strict;
use XML::Simple;
use DBI;

my $dbh = DBI->connect('DBI:mysql:MYDATABASE','user','password')
  or die DBI->errstr;

# Get an array of hashes
my $recs = $dbh->selectall_arrayref('SELECT * FROM contents',{ Columns => {} });

# Convert to XML where each hash element becomes an XML element
my $xml = XMLout( {record => $recs}, NoAttr => 1 );

print $xml;

$dbh->disconnect;


For a table with fields named "id", "entry", and "modified", the output would be:

<opt>
  <record>
    <id>1</id>
    <entry>1932 - 1939</entry>
    <modified>2005-04-15 22:24:44</modified>
  </record>
  <record>
    <id>2</id>
    <entry>Yet another entry</entry>
    <modified>2005-04-15 22:25:00</modified>
  </record>
  <record>
    <id>3</id>
    <entry>More stuff here</entry>
    <modified>2005-04-15 22:25:13</modified>
  </record>
</opt>

Convert HTML entities

Include this to convert those ampersands and angle brackets to proper entities. It can help with XML too but remember there are lots of other entities that need converting.

use HTML::Entities;

...

$html = encode_entities($string, '<>&"');

Oneliner - Print a File as Hex

perl -ne '@a=split"";for(@a){printf"%02x ",ord;print"\n"unless++$c % 20}' sample.txt

Expand Numerical Ranges

This rather long winded Perl subroutine returns an array of numbers expanded from a list such as 34,35,36,42-56,98-150. There are plenty of other ways to do this (eval comes to mind).

 sub expand {                                                              
  my $range = shift;            
  my @result; 
$range =~ s/[^\d\-\,]//gs; #remove extraneous characters
 my @items = split(/,/,$range);    
  foreach (@items){                 
    m/^\d+$/ and push(@result,$_) and next;  my ($start,$finish) = split /-/;   push(@result,($start .. $finish)) if $start < $finish;                    
  }                                 
  return @result;                        
 } 

Read a File with any Line Ending

Here is a quick way in Perl to read lines from a file regardless of whether it is Unix, Mac, or DOS.

my @lines = split(/\012\015?|\015\012?/,(join '',<FILE>));

UTF8 Curly Quotes to ASCII

Here's a cheap hack to convert UTF8 curly quotes to ASCII (but try to use CPAN module instead of this if you can).

 $xml =~ s/\xe2\x80\x99/\'/gs;
 $xml =~ s/\xe2\x80\x98/\'/gs;
 $xml =~ s/\xe2\x80\x9c/\"/gs;
 $xml =~ s/\xe2\x80\x9d/\"/gs;

Convert Emacs Region to HTML

Sometimes while I'm editing, I want to convert a region to HTML. I use Perl's HTML::FromText. First I create this script and call it tohtml.

#!/usr/bin/perl

 use HTML::FromText;
 use strict;

 my $text = join '',<>;
 my $html = text2html($text, urls => 1, email => 1, bold=>1, paras => 1, allcaps => 1, tables => 1, bullets => 1, underline=>1);

print $html;


Then from within Emacs, I select the region and do

C-x ESC-1 ESC-| tohtml RET

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS