[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] Bash Script Help



On Mon, May 23, 2005 at 09:50:12PM -0500, Colin Ingram wrote:
> Almut Behrens wrote:
> >
> > ... | perl -pe 's/^(\d+):(\d+):(\d+)/$1*60**2 + $2*60 + $3/e'
> >
> >in case the time string represents "hours:min:sec".
> >If it's "min:sec.msec" (looks like it to me...), then it'd be
> > 
> >
> its actually "[hours]:min:sec" (the secs have ms precision).

ah, I see.

> I assume I 
> can make the first subexpression match zero or one time.  In that 
> situation if the first subexpression doesn't match does $1=null?

...exactly (though it's 'undef', not null, strictly speaking).  And
the nice thing is that Perl doesn't segfault or throw fatal exceptions
in such cases...  it just works as expected.  If used in a numeric
context, an undefined value will just evaluate to 0, which is typically
what you want.

So, the above s/// statement simply has to be modified as follows

  s/^((\d+):)?(\d+):([\d.]+)/sprintf "%.3f", $2*60**2 + $3*60 + $4/e

as you may have figured out yourself in the meantime.

Or, taking advantage of the fact that any trailing garbage (':') does
not do any harm to string-to-number conversions in Perl, you can even
save one pair of parentheses ;) -- not universally recommended, though.

  s/^(\d+:)?(\d+):([\d.]+)/sprintf "%.3f", $1*60**2 + $2*60 + $3/e

(Alternatively, you could of course also write

  perl -pe '{} while s/^(\d+):([\d.]+)/$1*60+$2/e'

as another step to achieving obfuscation.  OK, I'm being silly.)

Almut



Reply to: