<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Marcel Grünauer</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/" />
    <link rel="self" type="application/atom+xml" href="http://blogs.perl.org/users/marcel_grunauer/atom.xml" />
    <id>tag:blogs.perl.org,2009-11-03:/users/marcel_grunauer//353</id>
    <updated>2013-02-22T15:49:10Z</updated>
    <subtitle>Marcel&apos;s Perl blog</subtitle>
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type Pro 4.38</generator>

<entry>
    <title>pathed - munge the Bash PATH</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2013/02/pathed---munge-the-bash-path.html" />
    <id>tag:blogs.perl.org,2013:/users/marcel_grunauer//353.4366</id>

    <published>2013-02-22T15:47:38Z</published>
    <updated>2013-02-22T15:49:10Z</updated>

    <summary>I wrote &quot;pathed&quot;, a tool to munge the Bash &quot;PATH&quot; environment variable. The Bash &quot;PATH&quot; environment variable contains a colon-separated list of paths. pathed - &quot;path editor&quot; - can split the path, append, prepend or remove elements, remove duplicates and...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>I wrote "pathed", a tool to munge the Bash "PATH" environment variable.</p>

<p>The Bash "PATH" environment variable contains a colon-separated list of paths. pathed - "path editor" - can split the path, append, prepend or remove elements, remove duplicates and reassemble it.</p>

<p><a href="http://marcelgruenauer.com/blog/2013/02/22/pathed/
">http://marcelgruenauer.com/blog/2013/02/22/pathed/</a></p>
]]>
        

    </content>
</entry>

<entry>
    <title>Redirect: http://perlservices.at</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2012/02/redirect-httpperlservicesat.html" />
    <id>tag:blogs.perl.org,2012:/users/marcel_grunauer//353.2865</id>

    <published>2012-02-23T16:32:49Z</published>
    <updated>2012-02-23T16:46:07Z</updated>

    <summary>I&apos;ve created a new blog at http://perlservices.at, a site which I intend to use to pimp offer my services, and will use that blog from now on. The design is not quite there yet. :)...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>I've created a new blog at <a href="http://perlservices.at/blog">http://perlservices.at</a>, a site which I intend to use to <strike>pimp</strike> offer my services, and will use that blog from now on. The design is not quite there yet. :)</p>
]]>
        

    </content>
</entry>

<entry>
    <title>5.10 regex features: Build a nested structure while matching</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/10/510-regex-features-build-a-nested-structure-while-matching.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.2243</id>

    <published>2011-10-02T17:05:46Z</published>
    <updated>2011-10-02T17:10:59Z</updated>

    <summary>In trying to learn 5.10 grammar-like regex features and wrote a program that, while matching simple Lisp-like constructs, builds up a data structure. This involves recursing into subpatterns, but I couldn&apos;t find a way to assemble the resulting tree from...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>In trying to learn 5.10 grammar-like regex features and wrote a program that, while matching simple Lisp-like constructs, builds up a data structure. This involves recursing into subpatterns, but I couldn't find a way to assemble the resulting tree from the bottom up. Therefore I used a stack.</p>

<p>Do you know of a better way of building the data structure with the given regex/grammar?</p>

<p>(I'm aware of Parse::RecDescent and Regexp::Grammars, but wanted to do this as simply as possible.)</p>

<pre><code>#!/usr/bin/env perl

# Exercising perl 5.10 regular expression features:
# Return a tree structure while matching simple Lisp-like constructs

use warnings;
use strict;
use 5.010;
use Test::More;
use Test::Differences;

sub parse {
    my $string = shift;
    # 'my @S' produces 'Variable "@S" will not stay shared' and failures
    our @S = ();
    # 'my @t' produces 'Can't localize lexical variable @t'
    our @t;

    # Use a stack because I can't see a way of localizing variables when
    # recursing into subpatterns.
    state $re = qr{
        (?&amp;tree)
        (?(DEFINE)
          (?&lt;tree&gt;
               \(
               (?{push @S, 'MARK'})
               (?&amp;element) (?: \s+ (?&amp;element) )*
               \)
               (?{
                   local @t;
                   while ((my $el = pop @S) ne 'MARK') { unshift @t, $el }
                   push @S, \@t;
                 })
          )
          (?&lt;element&gt;  (?&amp;value) | (?&amp;tree) )
          (?&lt;value&gt; (\w+) (?{ push @S, $^N }) )
        )
    }x;
    $string =~ $re;
    pop @S;
}

sub check {
    my ($string, $expect) = @_;
    eq_or_diff parse($string), $expect, $string;
}
check('(print)', ['print']);
check('(print foo bar baz)', [qw(print foo bar baz)]);
check('(print (foo 1 2) (bar 3 (baz 4 5)))',
    [ 'print', [ 'foo', '1', '2' ], [ 'bar', '3', [ 'baz', '4', '5' ] ] ]);
check('((foo (bar 1)) baz)', [ [ 'foo', [ 'bar', '1' ] ], 'baz' ]);
done_testing;
</code></pre>

<p>You can get the code at https://gist.github.com/1257636 .</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Being anti-social</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/08/being-anti-social.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.2143</id>

    <published>2011-08-29T17:37:03Z</published>
    <updated>2011-08-29T17:42:25Z</updated>

    <summary>A few days ago I deactivated my Twitter account and most other social networking accounts. It&apos;s not that I&apos;m vanishing off the face of the earth or anything like that - I&apos;ve just gotten disillusioned with &quot;social&quot; networking. It has...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>A few days ago I deactivated my Twitter account and most other social networking accounts. It's not that I'm vanishing off the face of the earth or anything like that - 
I've just gotten disillusioned with "social" networking. It has grown to be a kind of addiction; I checked Twitter etc. far too often, to the point of it being a distraction, but actually it wasn't a lot of real communication, it was more like people talking <em>at</em> you. I didn't find much "social" value in the whole thing.</p>

<p>I still program Perl for a living, and it'd be nice to see Perl friends, for example, in Frankfurt next year.</p>

<p>About all those CPAN modules - I've looked over the 100+ dists that are under my name on CPAN and have found that most of these I neither use anymore nor do I have any wish to maintain them. Most of them were related to an older work project and are probably not used outside of that.</p>

<p>There are only about six or so dists that I'm really using and maintaining. There are a few modules that others have expressed an interest in maintaining - mostly the Dist::Zilla plugins - and I've given them co-maint.</p>

<p>So, it's no big deal; just curbing my "social" presence.</p>

<p>(Actually, let's see about that Twitter account - as far as I can tell, you can still re-activate it within 30 days, so maybe the addiction might win... :) )</p>
]]>
        

    </content>
</entry>

<entry>
    <title>dip script to show DBI queries as they are prepared</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/07/dip-script-to-show-dbi-queries-as-they-are-prepared.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.1944</id>

    <published>2011-07-06T08:36:23Z</published>
    <updated>2011-07-06T08:41:23Z</updated>

    <summary><![CDATA[There's DBI_TRACE, but sometimes I just want to see the queries that are used in $dbh-&gt;prepare(). Here is a simple dip script to do that. dip -e 'before { warn ARGS(1) } call qr/DBI::.*::prepare/' foo.pl...]]></summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="dip" label="dip" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="dtrace" label="dtrace" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="perl" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>There's DBI_TRACE, but sometimes I just want to see the queries that are used in <code>$dbh-&gt;prepare()</code>. Here is a simple <a href="http://beta.metacpan.org/module/dip">dip</a> script to do that.</p>

<pre><code>dip -e 'before { warn ARGS(1) } call qr/DBI::.*::prepare/' foo.pl
</code></pre>
]]>
        

    </content>
</entry>

<entry>
    <title>Vim script to fix the current file&apos;s package name</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/07/vim-script-to-fix-the-current-files-package-name.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.1938</id>

    <published>2011-07-03T11:29:43Z</published>
    <updated>2011-07-03T12:19:52Z</updated>

    <summary>In our work project, there are lots of Test::Class-based modules, and they live in lib/ so other distributions can use them. Anyway, when writing a new module of tests, I don&apos;t start from an empty file but rather copy one...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="package" label="package" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="perl" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="vim" label="vim" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>In our work project, there are lots of Test::Class-based modules, and they live in lib/ so other distributions can use them. Anyway, when writing a new module of tests, I don't start from an empty file but rather copy one of the existing test modules.</p>

<p>So I have to change the package name, but I've long felt that this can be automated - after all, if the module file is lib/Foo/Bar.pm, vim should be able to deduce that this is package Foo::Bar and change the package name accordingly.</p>

<p>The script below does that; it makes a few assumptions: that your modules live in a lib/ directory; that the package line already exists (but presumably with the wrong name) and that the package name to be replaced is in the first line that starts with 'package', followed by the name.</p>

<p>It's simple enough so you can adapt it to your needs. I hope you find this useful!</p>

<pre><code>nnoremap &lt;Leader&gt;pa :&lt;C-u&gt;call PerlReplacePackageName()&lt;CR&gt;

function! PerlPackageNameFromFile()
    let filename = expand('%:p')
    let package = substitute(filename, '^.*/lib/', '', '')
    let package = substitute(package, '\.pm$', '', '')
    let package = substitute(package, '/', '::', 'g')
    return package
endfunction

function! PerlReplacePackageName()
    let package = PerlPackageNameFromFile()
    let pos = getpos('.')
    1,/^package\s/s/^package\s\+\zs[A-Za-z_0-9:]\+\ze\(\s\+{\|;\)/\=package/
    call setpos('.', pos)
endfunction
</code></pre>

<p>Thanks to kana1 for his <a href="https://gist.github.com/1062187">corrections</a>!</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Vienna.pm donates $10.000 for Perl 5 Core Maintenance</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/06/viennapm-donates-10000-for-perl-5-core-maintenance.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.1918</id>

    <published>2011-06-28T20:19:45Z</published>
    <updated>2011-06-28T20:22:53Z</updated>

    <summary>domm writes: The Perl 5 Core Maintenance Fund aims to raise $25.000 to to pay for Nicholas Clark and Dave Mitchell to work for 3 months on the Perl 5 core, fixing bugs and making other improvements. Vienna.pm decided to...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="mongers" label="mongers" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="p5p" label="p5p" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="perl" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="vienna" label="vienna" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="yapc" label="yapc" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p><a href="http://vienna.pm.org/10_000_dollar_for_the_perl5_core_maintaince_fund.html">domm writes</a>:</p>

<p><i>The Perl 5 Core Maintenance Fund aims to raise $25.000 to to pay for Nicholas Clark and Dave Mitchell to work for 3 months on the Perl 5 core, fixing bugs and making other improvements.</i></p>

<p><p><i>Vienna.pm decided to set aside $10.000 as "match funding" - ie for every $1 that someone else donates, Vienna.pm donate $1, until $10,000 + $10,000 is raised, and only 20% remains to reach the target. The hope is that "match funding" will encourage people to donate a bit more themselves than a simple unconditional donation.</i><p></p>
]]>
        

    </content>
</entry>

<entry>
    <title>dip.pm: Dynamic instrumentation like DTrace, using aspects</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/06/dippm-dynamic-instrumentation-like-dtrace-using-aspects.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.1915</id>

    <published>2011-06-28T09:51:49Z</published>
    <updated>2011-06-28T10:43:53Z</updated>

    <summary>I like DTrace and wanted to have at least part of its power for Perl progams, beyond the DTrace probes already provided by perl. So I used Aspects to create dip.pm. Allow me to quote from the manpage: $ dip...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="aop" label="AOP" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="aspect" label="Aspect" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="dtrace" label="DTrace" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="instruments" label="instruments" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="perl" label="Perl" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>I like DTrace and wanted to have at least part of its power for Perl progams, beyond the DTrace probes already provided by perl. So I used Aspects to create dip.pm. Allow me to quote from the manpage:</p>

<pre><code>$ dip -e 'aspect Profiled =&gt; call qr/^Person::set_/' myapp.pl
$ dip -s toolkit/count_new.dip -- -S myapp.pl
$ dip -e 'before { count("constructor", ARGS(1), ustack(5)); $c{total}++ }
    call qr/URI::new$/' test.pl

$ cat quant-requests.dip
# quantize request handling time, separated by request URI
before { $ts_start = [gettimeofday] }
    call qr/Dancer::Handler::handle_request/;
after { quantize ARGS(1)-&gt;request_uri =&gt; 10**6*tv_interval($ts_start) }
    call qr/Dancer::Handler::handle_request/;
$ dip -s request-quant.dip test.pl
...
/
       value  ------------------ Distribution ------------------ count
        1024 |                                                   0
        2048 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@    95
        4096 |@@                                                 4
        8192 |                                                   0
       16384 |@                                                  1
       32768 |                                                   0

/login
       value  ------------------ Distribution ------------------ count
         512 |                                                   0
        1024 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                70
        2048 |@@@@@@@@@@@@@@@                                    30
        4096 |                                                   0
</code></pre>

<h1>DESCRIPTION</h1>

<p><code>dip</code> is a dynamic instrumentation framework for troubleshooting Perl
programs in real time. <code>dip</code> can provide fine-grained information,
such as a log of the arguments with which a specific function is being
called.</p>

<p>Conceptually, <code>dip</code> sits on top of <a href="http://search.cpan.org/perldoc?Aspect">Aspect</a> and uses pointcuts and
advice - to use Aspect-oriented programming jargon - to define dynamic
instrumentation. These instruments are applied to the program from the
outside, without having to change the program code at all. While most
<code>dip</code> scripts will consist of aspect-oriented instrumentation, they
can also use the full power of Perl.</p>

<p><code>dip</code> aims to bring some of the power of DTrace to perl. Therefore it
is useful to stick to DTrace terminology. <code>dip</code> pointcuts resemble
DTrace "probes"; <code>dip</code> advice resembles DTrace "actions".</p>

<p>Whenever the condition for a probe is met, the associated action
is executed; the probe "fires". A typical probe might fire when
a certain function is entered or exited. The probe's action may
analyze the run-time situation by accessing the call stack and context
variables and evaluating expressions; it can then print out or log
some information, record it in a database, or modify variables - an
action is, after all, pure Perl code. Using variables allows probes to
pass information to each other, allowing them to cooperatively analyze
the correlation of different events. For example, a probe that fires
when a function is entered could record the current time; another
probe that fires when that function is exited could record how much
time the function took.</p>

<p>Because of the nature of Aspect-oriented programming in Perl, you only
pay for what you use. When probes are defined, all existing possible
locations for running the action are examined, and the probe is only
activated for those locations that match the probe's condition.</p>

<h2>Output</h2>

<p>At the end of your program run, during <code>END</code> time, all aggregators -
see below - will dump their results. Also any other hashes you have
written to in your dip scripts will be dumped.</p>

<p>For example, if you simply wanted to know which kinds of objects have
been instantiated at least once, you could use:</p>

<pre><code>before { $c{total}++ } call qr/::new$/
</code></pre>

<p>and then <code>%c</code> will be dumped.</p>

<h2>Aggregating functions</h2>

<p><code>dip</code> provides aggregating functions that help in understanding a set
of data. You can keep counts of occurrences, or quantize data, much
like with DTrace.</p>

<p>The <code>quantize</code> aggregating function generates a power-of-two
distribution - see its documentation.</p>

<h1>FUNCTIONS</h1>

<h2>import</h2>

<p>Remembers the dip script given on the command-line so we can run it in
<code>instrument()</code>. Complains if there was no dip script. The <code>--delay</code>
option is passed in this way as well.</p>

<h2>instrument</h2>

<p>Evaluates the dip script we remembered in <code>import()</code>. Dies if there
was a problem evaluating it.</p>

<p>Normally this function will be called automatically during <code>INIT</code>
time, but you can delay by giving the <code>--delay</code> option to <code>dip</code>; you
would use this if your program loads other code at runtime - using
<code>do()</code>, for example - that needs to be instrumented as well. In that
case you have manually activate the instrumentation using:</p>

<pre><code>$dip::dip &amp;&amp; $dip::dip-&gt;();
</code></pre>

<h2>run</h2>

<p>Convenience function that takes a filename and runs the file via
<code>do()</code>. This is what <code>dip -s</code> uses. For example:</p>

<pre><code>dip -s myscript.dip myapp.pl
</code></pre>

<p>is turned into:</p>

<pre><code>dip -e 'run q!$file!' myapp.pl
</code></pre>

<p>and ultimately</p>

<pre><code>perl -Mdip='run q!$file!' myapp.pl
</code></pre>

<h2>ustack</h2>

<p>Returns a concise stack trace. Takes an argument of how many levels
deep the stack trace should be; the default is 20 levels. Stack frames
that point to a package name in the <code>Aspect::</code> or <code>dip</code> namespace
are omitted.</p>

<p>Example: count how many times a <code>XML::LibXML::NodeList</code> object is
created, and keep a separate counter for each place it is created
from, remembering three stack frames for each place:</p>

<pre><code>before { count "constructor", ARGS(0), ustack(3) }
    call qr/XML::LibXML::NodeList::new$/
</code></pre>

<h2>cluck</h2>

<p>Returns what <a href="http://search.cpan.org/perldoc?Carp">Carp</a>'s <code>cluck()</code> would return, again with <code>Aspect::</code>
and <code>dip</code> namespaces omitted.</p>

<h2>count</h2>

<p>This aggregator function takes a counter name and a value and keeps a
count of how often this value was seen for this counter.</p>

<p>You can pass several values; they will be concatenated using newlines.
See the example for <code>ustack()</code>.</p>

<p>Example: For each class, count how many objects are created. Also keep
a total count.</p>

<pre><code>before { count("constructor", ARGS(0)); $c{total}++ }
    call qr/::new$/
</code></pre>

<h2>dump_var</h2>

<p>Convenience method to dump a variable like <a href="http://search.cpan.org/perldoc?Data::Dumper">Data::Dumper</a> does.</p>

<p>Example: Show all requests a <a href="http://search.cpan.org/perldoc?Dancer">Dancer</a> web application handles:</p>

<pre><code>before { dump_var ARGS(1) }
    call qr/Dancer::Handler::handle_request/
</code></pre>

<h2>rtrim</h2>

<p>Convenience function to right-trim a string.</p>

<h2>rref</h2>

<p>Convenience function that, if given a string - for example, a package
name -, just returns the string, but if given an object, it returns
that object's class.</p>

<p>Useful if objects you want to instrument are sometimes created by
calling <code>new()</code> on existing objects:</p>

<pre><code>before { count("constructor", rref ARGS(0)) } call qr/::new$/
</code></pre>

<h2>ARGS</h2>

<p>Convenience function to access the arguments of a function that
you are instrumenting. <code>ARGS(0)</code>, for example, returns the first
argument. You can use several argument indices; in this case the
indicated function arguments will be stringified and concatenated with
a space.</p>

<p><code>ARGS(0)</code> is equivalent to <code>$_-&gt;{args}[0]</code>; <code>ARGS(1,2)</code> is equivalent to
<code>join ' ' =&gt; ARGS(0), ARGS(1)</code> - see <a href="http://search.cpan.org/perldoc?Aspect">Aspect</a> for the kind of context information that is passed to advice code.</p>

<h2>quantize</h2>

<p>This aggregator function takes a name, or an reference to a list of
names, and a value. For each name, it keeps track of a power-of-two
frequency distribution of the values of the specified expressions.
Increments the value in the highest power-of-two bucket that is less
than the specified expression.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Perl QA Hackathon 2011 in Amsterdam</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/05/perl-qa-hackathon-2011-in-amsterdam.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.1745</id>

    <published>2011-05-10T19:30:19Z</published>
    <updated>2011-05-10T19:34:50Z</updated>

    <summary>Finally I&apos;ve uploaded pictures from the Perl QA Hackathon 2011, which took place in Amsterdam from 16th-18th of April. Photos It was a very enjoyable event - good company, good code, good beer. Thanks to Philippe Bruhat (BooK) for organizing...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="qahackathonamsterdambooking" label="qa hackathon amsterdam booking" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>Finally I've uploaded pictures from the <a href="http://2011.qa-hackathon.org/qa2011/">Perl QA Hackathon 2011</a>, which took place in Amsterdam from 16th-18th of April.</p>

<p><a href="http://www.flickr.com/photos/hanekomu/sets/72157626672181794/">Photos</a></p>

<p>It was a very enjoyable event - good company, good code, good beer. Thanks to Philippe Bruhat (BooK) for organizing it; to Booking.com for their offices and sponsorship; and to Vienna.pm for their sponsorship, which also helped to cover my travel and accommodation costs.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Using each() to iterate over an array</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/01/using-each-to-iterate-over-an-array.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.1384</id>

    <published>2011-01-21T09:15:03Z</published>
    <updated>2011-01-20T23:41:47Z</updated>

    <summary>In perl 5.12, each() - as well as keys() and values() - works on arrays, where previously these functions were restricted to hashes. When iterating over an array, each() returns both the index and the value. my @x = 50..59;...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>In perl 5.12, <code>each()</code> - as well as <code>keys()</code> and <code>values()</code> - works on arrays,
where previously these functions were restricted to hashes. When iterating over
an array, <code>each()</code> returns both the index and the value.</p>

<pre><code>my @x = 50..59;
while(my ($i, $v) = each @x) {
    say "index $i, value $v";
}
</code></pre>

<p>will print:</p>

<pre><code>index 0, value 50
index 1, value 51
index 2, value 52
index 3, value 53
index 4, value 54
index 5, value 55
index 6, value 56
index 7, value 57
index 8, value 58
index 9, value 59
</code></pre>

<p>Previously you could iterate over the array values but had to keep a counter
yourself, or you could have a for-loop counting up, but then you had to
retrieve the current array element separately. So this new construct saves
quite a bit of code.</p>

<p>On a related note, if you need to iterate over an array, taking several
elements at a time, you can use the well-known idiom:</p>

<pre><code>while (my ($f, $g) = splice @x, 0, 2) {
    say "f $f, g $g";
}
</code></pre>

<p>which will print:</p>

<pre><code>f 50, g 51
f 52, g 53
f 54, g 55
f 56, g 57
f 58, g 59
</code></pre>
]]>
        

    </content>
</entry>

<entry>
    <title>Caching multi-statement computations using an anonymous subroutine</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2011/01/caching-multi-statement-computations-using-an-anonymous-subroutine.html" />
    <id>tag:blogs.perl.org,2011:/users/marcel_grunauer//353.1383</id>

    <published>2011-01-20T22:14:28Z</published>
    <updated>2011-01-20T22:14:36Z</updated>

    <summary>Suppose that a subroutine gets called several times and that in the subroutine you need to use some computational result that stays the same for every call. You could use a state variable or an our variable. sub foo {...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>Suppose that a subroutine gets called several times and that in the subroutine
you need to use some computational result that stays the same for every call.
You could use a <code>state</code> variable or an <code>our</code> variable.</p>

<pre><code>sub foo {
    # ...

    state $some_value //= ... some computation ...;

    # ...
}
</code></pre>

<p>Using the defined-or operator, the value will only be computed the first time
the subroutine is called.</p>

<p>But what if the computation takes several statements? You could move it to its
own subroutine and call it with a single statement, or you might resort to
something like:</p>

<pre><code># NOT IDIOMATIC
sub foo {
    # ...

    state $some_value;
    unless (defined $some_value) {
        # ... some more ...
        # ... intensive ...
        # ... computation ...
        $some_value = ...;
    }

    # ...
}
</code></pre>

<p>The problem is that we need to write <code>$some_value</code> three times.</p>

<p>But a more idiomatic way is to use an anonymous subroutine and call it
in-place:</p>

<pre><code>sub foo {
    # ...

    state $some_value //= sub {
        # ... some more ...
        # ... intensive ...
        # ... computation ...
    }-&gt;();

    # ...
}
</code></pre>
]]>
        

    </content>
</entry>

<entry>
    <title>Obfuscation: Comparing the size of two arrays</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2010/12/obfuscation-comparing-the-size-of-two-arrays.html" />
    <id>tag:blogs.perl.org,2010:/users/marcel_grunauer//353.1271</id>

    <published>2010-12-22T13:02:42Z</published>
    <updated>2010-12-22T13:03:58Z</updated>

    <summary>~~@x ~~ ~~@y is true if @x and @y have the same number of elements. This rather elegant obfuscation uses the smart match operator as well as double bitwise negation....</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="obfuscation" label="obfuscation" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<pre><code>~~@x ~~ ~~@y
</code></pre>

<p>is true if <code>@x</code> and <code>@y</code> have the same number of elements.</p>

<p>This rather elegant obfuscation uses the smart match operator as well as double
bitwise negation.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>One-liner to count the number of lines in a file</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2010/12/one-liner-to-count-the-number-of-lines-in-a-file.html" />
    <id>tag:blogs.perl.org,2010:/users/marcel_grunauer//353.1270</id>

    <published>2010-12-22T12:53:39Z</published>
    <updated>2010-12-22T13:00:30Z</updated>

    <summary>There is a cute Perl one-liner to count the number of lines in a file: perl -nE&apos;}{say$.&apos; foo.txt Let&apos;s see how perl parses this one-liner: $ perl -MO=Deparse -nE&apos;}{say$.&apos; foo.txt BEGIN { $^H{&apos;feature_unicode&apos;} = q(1); $^H{&apos;feature_say&apos;} = q(1); $^H{&apos;feature_state&apos;} =...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="oneliner" label="one-liner" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>There is a cute Perl one-liner to count the number of lines in a file:</p>

<pre><code>perl -nE'}{say$.' foo.txt
</code></pre>

<p>Let's see how perl parses this one-liner:</p>

<pre><code>$ perl -MO=Deparse -nE'}{say$.' foo.txt 
BEGIN {
    $^H{'feature_unicode'} = q(1);
    $^H{'feature_say'} = q(1);
    $^H{'feature_state'} = q(1);
    $^H{'feature_switch'} = q(1);
}
LINE: while (defined($_ = &lt;ARGV&gt;)) {
    ();
}
{
    say $.;
}
-e syntax OK
</code></pre>

<p>So <code>-E</code> turns on the special features (we only use <code>say</code> here) and <code>-n</code>
provides the boilerplate code. As for <code>$.</code>, <code>perldoc perlvar</code> says that it is
the current line number for the last filehandle accessed.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>vim: add a &apos;use&apos; statement without moving the cursor</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2010/12/vim-add-a-use-statement-without-moving-the-cursor.html" />
    <id>tag:blogs.perl.org,2010:/users/marcel_grunauer//353.1265</id>

    <published>2010-12-21T21:09:51Z</published>
    <updated>2010-12-21T21:13:59Z</updated>

    <summary><![CDATA[You're writing Perl code in vim and have just typed a package name - maybe you want to create an object of this class: some_statement; my $o = Some::Class-&gt;new; do_something_with($o); You obviously need to write use Some::Class at the top....]]></summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="use" label="use" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="vim" label="vim" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>You're writing Perl code in vim and have just typed a package name - maybe you
want to create an object of this class:</p>

<pre><code>some_statement;
my $o = Some::Class-&gt;new;
do_something_with($o);
</code></pre>

<p>You obviously need to write <code>use Some::Class</code> at the top. So you either move
the cursor near the top and add the line, then jump to the previous line
number, or maybe you split the window, move to the new viewport, make the
change, then close that viewport.</p>

<p>There is a better way. Here is a vim function for adding a <code>use</code> statement to
the top of your file. I prefer it to go below my last existing <code>use</code> statement,
except for special cases like <code>use strict</code>, <code>use constant</code> etc. If there isn't
any such regular <code>use</code> statement, I want the new <code>use</code> statement to appear
below the <code>ABSTRACT</code> (a Dist::Zilla-related comment) or below the <code>package</code>
statement. Failing that, I want the <code>use</code> statement to appear below any
existing <code>use</code> statement. If there isn't one of those either, below the shebang
line. If we don't even have that, just put it at the top of the file.</p>

<p>Your aesthetic requirements may vary, so change the function accordingly.</p>

<p>This is my first real Vim script function that I've written, so excuse the
'baby Vim'.</p>

<pre><code>" perl: add 'use' statement
"
" make sure you have
"   setlocal iskeyword=48-57,_,A-Z,a-z,:
" so colons are recognized as part of a keyword

function! PerlAddUseStatement()
    let s:package = input('Package? ', expand('&lt;cword&gt;'))
    " skip if that use statement already exists
    if (search('^use\s\+'.s:package, 'bnw') == 0)
        " below the last use statement, except for some special cases
        let s:line = search('^use\s\+\(constant\|strict\|warnings\|parent\|base\|5\)\@!','bnw')
        " otherwise, below the ABSTRACT (see Dist::Zilla)
        if (s:line == 0)
            let s:line = search('^# ABSTRACT','bnw')
        endif
        " otherwise, below the package statement
        if (s:line == 0)
            let s:line = search('^package\s\+','bnw')
        endif
        " if there isn't a package statement either, put it below
        " the last use statement, no matter what it is
        if (s:line == 0)
            let s:line = search('^use\s\+','bnw')
        endif
        " if there are no package or use statements, it might be a
        " script; put it below the shebang line
        if (s:line == 0)
            let s:line = search('^#!','bnw')
        endif
        " if s:line still is 0, it just goes at the top
        call append(s:line, 'use ' . s:package . ';')
    endif
endfunction

map ,us :&lt;C-u&gt;call PerlAddUseStatement()&lt;CR&gt;
</code></pre>
]]>
        

    </content>
</entry>

<entry>
    <title>Scalar context gotchas</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/marcel_grunauer/2010/12/scalar-context-gotchas.html" />
    <id>tag:blogs.perl.org,2010:/users/marcel_grunauer//353.1264</id>

    <published>2010-12-21T19:48:54Z</published>
    <updated>2010-12-21T19:57:49Z</updated>

    <summary>On Twitter, Curtis Poe (@OvidPerl) posted some interesting and unintuitive Perl code; I&apos;ve slightly reformatted it and changed some values for the sake of the following discussion. use Data::Dumper; sub boo { 4,5,6 } my @x = ( boo() ||...</summary>
    <author>
        <name>Marcel Grünauer</name>
        <uri>http://perlservices.at/</uri>
    </author>
    
    <category term="array" label="array" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="context" label="context" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="list" label="list" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="scalar" label="scalar" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/marcel_grunauer/">
        <![CDATA[<p>On Twitter, Curtis Poe (<a href="http://twitter.com/OvidPerl">@OvidPerl</a>)
<a href="http://twitter.com/#!/OvidPerl/status/17244407778508800">posted</a> some
interesting and unintuitive Perl code; I've slightly reformatted it and changed
some values for the sake of the following discussion.</p>

<pre><code>use Data::Dumper;
sub boo { 4,5,6 }
my @x = ( boo() || 5,8,7);
print Dumper \@x;
</code></pre>

<p>What do you think this prints?</p>

<p>Let's look at some simpler examples of code:</p>

<pre><code>$ perl -le'@x = (4,5,6,7,8); $y = @x; print $y'
5
</code></pre>

<p>An array like <code>@x</code>, in scalar context, evaluates to the number of elements in
that array. In this case, <code>@x</code> contains five elements.</p>

<pre><code>$ perl -le'$y = (4,5,6,7,8); print $y'
8
</code></pre>

<p>A list, as opposed to an array, returns the last element in scalar context - in
this case, 8.</p>

<p>Let's see how perl parses this line. We can use the B::Deparse module with the
<code>-p</code> option, which adds extra parentheses to make the structure clearer.</p>

<pre><code>$ perl -MO=Deparse,-p -le'$y = (4,5,6,7,8); print $y'
BEGIN { $/ = "\n"; $\ = "\n"; }
($y = ('???', '???', '???', '???', 8));
print($y);
-e syntax OK
</code></pre>

<p>As you can see, the unused constant values have been optimized away.</p>

<p><code>perldoc perldata</code> says this about arrays and lists in scalar context:</p>

<blockquote>
  <p>If you evaluate an array in scalar context, it returns the length of the
array. (Note that this is not true of lists, which return the last
value, like the C comma operator, nor of built-in functions, which
return whatever they feel like returning.)</p>
</blockquote>

<p>And finally:</p>

<pre><code>$ perl -le'$y = (4..8); print $y'
</code></pre>

<p>This prints an empty line. You might have thought that this is the same as the
line with the list above, but the range operator is somewhat different. In list
context, it does indeed return a list of values counting from the left value to
the right value. However, in scalar context, the range operator behaves like a
flip-flop, starting out with a false value, which stringifies to an empty
string.</p>

<p><code>perldoc perlop</code> says this about the range operator:</p>

<blockquote>
  <p>In scalar context, ".." returns a boolean value. The operator is
bistable, like a flip-flop, and emulates the line-range (comma) operator
of sed, awk, and various editors. Each ".." operator maintains its own
boolean state, even across calls to a subroutine that contains it. It is
false as long as its left operand is false. Once the left operand is
true, the range operator stays true until the right operand is true,
<em>AFTER</em> which the range operator becomes false again.</p>
</blockquote>

<p>After this discussion, you probably know what the program at the beginning of
this post prints. Let's look at how perl parses it:</p>

<pre><code>$ perl -MO=Deparse,-p test.pl 
use Data::Dumper;
sub boo {
    (4, 5, 6);
}
(my(@x) = ((boo() || 5), 8, 7));
print(Dumper((\@x)));
test.pl syntax OK
</code></pre>

<p>If we run the program, it prints:</p>

<pre><code>$ perl test.pl 
$VAR1 = [
          6,
          8,
          7
        ];
</code></pre>

<p>The expression <code>(boo() || 5)</code> is the same as <code>((4, 5, 6) || 5)</code> and since a
list returns the last value in scalar context, this is the same as <code>(6 || 5)</code>,
which is 6.</p>
]]>
        

    </content>
</entry>

</feed>
