Monthly Archives: October 2005

Passing a filehandle as parameter

To keep things maintainable we split our program in modules, classes, functions… In perlsub from the execellent perl documentation you can lookup the syntax of how to use functions. Offcourse, you have to digg pretty deep to find out how you can pass a filehandle:

# clientproc(*STDOUT);
# pass the socket
clientproc(*CH);

sub clientproc
{
  $fh = shift;
  print $fh "hello world";
}

a little hint for writing and testing a script

I noticed that most people think Vim sucks and they constantly perform the following keystrokes:

:wq
perl somefile.pl
vim somefile.pl

Here is the first trick, you don’t need to exit vim to perform a command. Simply type the following while you’re in vim:

:!perl somefile.pl

Offcourse, you don’t want to type the filename all the time, so you use the following:

:!perl %

Now, if you are using a different scripting language it might be more portable to make the file executable (chmod u+x) and make sure the Shebang points to the right interpreter. Your script would be something like the following then:

#!/usr/bin/env perl
use strict;
use warnings;
use Socket;

Now all you have to do is type the following in vim and your script will be executed:

:!%

I noticed that the :!% trick doesn’t work when your script is in your current working directory. This is how you can make it work:

:!./%

I also noticed that before you execute this command you always need to type :w to save the changes. To automate this i’ve added the following to my ~/.vimrc file:

map ,r :w<cr>:!./%</cr><cr>
</cr>

Now all i have to type is the following:

,r

For other tricks and hints you have to check out Vi-IMproved.org.

Odd behaviour with arrays

A while ago i was really stumbled by the behaviour of a server. This problem solved itself after the sysadmin noticed that he forgot to upgrade ionCube after a php upgrade.Here is the code that i ran:

$array = array();
$array[] = array('name' => 'row1', 'value' => '1');
$array[] = array('name' => 'row2', 'value' => '3');
$array[] = array('name' => 'row3', 'value' => '2');

foreach($array as $row)
{
  print_r($row);
  echo "<br />";
}

The expected output is:

Array ( [name] => row1 [value] => 1 )
Array ( [name] => row2 [value] => 3 )
Array ( [name] => row3 [value] => 2 )

For some odd reason this is the output i got:

Array ( [0] => Array ( [name] => row1 [value] => 1 ) [1] => 0 )
Array ( [0] => Array ( [name] => row2 [value] => 3 ) [1] => 1 )