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 13 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>

Post XML using curl

You can use curl on the command line to do a POST to an endpoint.

echo '<doc><item>Some content.</item></doc>' | curl -X POST -H 'Content-type: text/xml' -d @- http://example.com/restapi


This is handy for adding web services to applications that do not do web services but can do command lines--FileMaker for example.

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, '<>&"');

XSLT Alternating Colors for HTML Table Rows

This attaches a style attribute to the tr tag, but only on every other tag.

<xsl:template match="my_repeating_item">
<tr>
  <xsl:if test="position() mod 2 != 1">
    <xsl:attribute  name="style">background-color:#dddddd</xsl:attribute>
  </xsl:if>
  <xsl:apply-templates/>
</tr>
<xsl:template>

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>));
« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS