Saturday, February 14, 2015

Perl Magic with split

How come even perldoc -f split doesn't show such stuff? Surprised that python and ruby have taken over?

$s = 'JP,w,l,m,*,/cygdrive/c/Tools/LTspiceIV/lib/sym/pjf.asy'

You want to get w, l and m in an array..

@info = split( /,\s*\*\s*,/ , $s);
@info = reverse ( split( /,/ , $info[0] ) );
@info = reverse( @info[0..$#info-1] );

okay, maybe this is looking a bit contrived. But, anyway, I started, I might as well finish :

@info = ( split( /,/ , ( split( /,\s*\*\s*,/ , $s) )[0] ) )[1..10]

Okay, a bit of cheating there - you have to know your data - so that the magic "10" is big enough..
Actually, that's not a good one. DON'T USE IT.. You wish they would support [1..] with the 2nd argument omitted.

Use
@info = split( /,/ , ( split( /,\s*\*\s*,/ , $s) )[0] );
@info = @info[1..$#info];

Did you know that the range operator also behaves like a bistable flip-flop in such a case :

if( $a .. $b ) {

}

First, it returns true only if $a is true. After that, it ignores $a and only returns true if $b is true, and so on..

Here's my rookie mistake of the day (after more than a decade with perl) :

    $is_cell = 1 if $subin =~ /^\s*$/s;

When what I really want is for $is_cell to be set to 0 when the match fails. Duh!

No comments: