I’d like to start posting code on my blog so I’m testing out a syntax highlighter plugin. This post will likely go through several iterations as I see what it can do and how to do it.
Here’s some ruby:
[ruby]
def addPages(urls)
return false unless urls
urls.each{ |u| @queue << PageFactory.newPage(u) }
@queue.uniq! # Get rid of dupes.
end
[/ruby]
Here's some Perl:
[perl]
my @text = ( 'here', 'are', 'some', 'words' );
my $offset = 0;
print join(' ', map { choppedCase($_) } @text );
# Convert a string to "ChOpPeD cAsE"
sub choppedCase
{
my $word = shift;
my @chars = split('', $word);
my $char_count = scalar(@chars);
for (my $i = $offset; $i < $char_count; $i+=2)
{
$chars[$i] = uc($chars[$i]);
}
# Track odd length words so we constantly alternate in a string
if ($char_count % 2)
{
$offset = $offset == 0 ? 1 : 0;
}
return join('', @chars);
}
[/perl]
Here's some PHP
[PHP]
// Pattern to match the directory path that a file is in
$dir_pattern = "@(/.*)/[^/]*$@";
// Take a path that's (possibly) relative to the directory that the script is executing in
// and convert it to an absolute path.
function absolutize($path)
{
global $dir_pattern;
// Only operate on paths that are relative
if (substr($path, 0, 1) == '.' && preg_match($dir_pattern, $_SERVER['PHP_SELF'], $matches))
$path = implode('', array($matches[1], '/', $path));
$path_bits = explode('/', $path);
$elms = array();
foreach ($path_bits as $bit)
{
if ($bit == '' || $bit == '.')
continue;
if ($bit == '..') {
array_pop($elms);
continue;
}
$elms[]= $bit;
}
// Push an empty string on top so that we get a leading / when we implode
array_unshift($elms, '');
return implode('/', $elms);
}
[/PHP]
I just realized that I've coded in all three of these languages this week - plus JavaScript (can't find a good sample to post).
Update
JavaScript
[javascript]
// Add commas to a long number to make it more readable.
// Currently only supports whole numbers.
var addCommas = function(aNumber)
{
// Convert our number to an array and reverse it so that
// we can easily work from most significant digits down
// to least significant
var bitsR = (aNumber.toString().split(”)).reverse();
for (var i = bitsR.length – 1; i>2; i–)
if (i % 3 == 0)
bitsR.splice(i, 0, ‘,’);
// Return our array with commas added back to the proper order
// for display on the screen.
return bitsR.reverse().join(”);
};
[/javascript]