SUMMARY Re: sh loop variable and "double indirection"
Dennis Davis
ccsdhd at gdt.bath.ac.uk
Wed Feb 13 04:37:49 AEST 1991
In article <5081 at acorn.co.uk> steve at acorn.co.uk (Steve "daffy" Hunt) writes:
>In article <1991Feb5.003613.21081 at shibaya.lonestar.org> afc at shibaya.lonestar.org (Augustine Cano) writes:
>>
>>
>>I didn't anticipate the great response I got to my questions. This
>>newsgroup is an important resource. Many thanks to the following people,
>>whose summary of responses follow:
>
>... more deleted...
>
>I only just subscribed to this newsgroup, so this is rather late, but
>my favourite solution to the loop index problem is the following shell
>function (just inline it if your shell does not support functions).
>
># usage: range start end [step]
>
>range () {
> echo "[li p ${3-1} + d si $2!<a] sa ${1}silax" | dc
>}
>
>I don't guarantee that your version of dc will be happy with that, but
>it works for me! Making it count backwards, etc, is left as an exercise.
>
> Steve
>
>--
> Steve Hunt steve at acorn.co.uk
I've always found that languages such as 'dc' are very much
write-only languages. This is probably a reflection on me rather
than on the language itself. I'd prefer to write the above more
verbosely using 'bc', as something like:
range ()
{ set `echo $@ | tr '-' '_'`
echo "if (${3-1} < 0)
{ for (i=$1; i>=$2; i=i+${3-1}) i }
if (${3-1} > 0)
{ for (i=$1; i<=$2; i=i+${3-1}) i }" | bc
}
The 'set' command is there as a sop to syntactic sugar. 'dc' and
'bc' require that negative numbers are preceeded by a underline
instead of a minus sign. The 'set' command enables you to write
them more naturally using a minus sign, eg 'range -5 -10 -1'.
The above has (for me) the overwhelming advantages that I can
understand it both now *and* in the future.
... all this is purely academic of course. No doubt there are far
more elegant solutions using awk, perl etc etc ...
--
Dennis Davis JANET: D.H.Davis at UK.AC.BATH
University of Bath UUCP: ...!mcsun!ukc!gdr!D.H.Davis
Bath, BA2 7AY EARN/BITNET: D.H.Davis%uk.ac.bath at UKACRL
England INTERNET: D.H.Davis%bath.ac.uk at nsfnet-relay.ac.uk
More information about the Comp.unix.shell
mailing list