[net.unix] zero-trip foreach loops

lamy@utai.UUCP (Jean-Francois Lamy) (10/05/86)

Is there an easy way to have csh foreach loops that don't complain if the
pattern given does not match any file, as may occur in the inner loop of this
bit of code:

foreach font (*.tfm)
    set fontname = `basename $font .tfm`
    foreach size ($fontname.*pxl)
    ...
    end
end

I've tried 

foreach size (`ls -1 $fontname.*pxl`).  

This stops the script from aborting, but still gives me the stupid 'No match'
message.  Gee, even FORTRAN does zero-trip DO loops these days...

Jean-Francois Lamy
AI Group, Dept of Computer Science     CSNet: lamy@ai.toronto.edu
University of Toronto		       EAN:   lamy@ai.toronto.cdn
Toronto, ON, Canada M5S 1A4	       UUCP:  lamy@utai.uucp

chris@umcp-cs.UUCP (Chris Torek) (10/08/86)

In article <2494@utai.UUCP> lamy@utai.UUCP (Jean-Francois Lamy) writes:
>Is there an easy way to have csh foreach loops that don't complain if the
>pattern given does not match any file, as may occur in the inner loop of this
>bit of code:
>
>    set fontname = `basename $font .tfm`
>    foreach size ($fontname.*pxl)
>    ...
>    end

The problem is not foreach, but *.

    foreach foo ()
	echo $foo
    end

works fine.

The C shell's globber can be made to behave much like the Bourne
shell's by setting the variable `nonomatch':

    set nonomatch
    foreach size ($fontname.*pxl)
    ...

This is not really ideal, as a lack of matches will then cause
the loop to run once, with `size' set to, e.g., `amtex10.*pxl'.

>I've tried 
>    foreach size (`ls -1 $fontname.*pxl`).  
>This stops the script from aborting, but still gives me the stupid
>'No match' message.

If you `set nonomatch', this will not complain about `no match';
however, `ls' will complain `amtex10.*pxl not found'.

Personally, I would stick to `sh', and add a check for `no match':

for font in *.tfm; do
	fontname=`basename $font .tfm`
	for size in $fontname.*pxl; do
		case $size in
		"$fontname.*pxl") ;;	# ignore `no match' name
		*)	...
		esac
	done
done
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 1516)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris@umcp-cs		ARPA:	chris@mimsy.umd.edu

dberg@cod.UUCP (David I. Berg) (10/22/86)

In article <2494@utai.UUCP>, lamy@utai.UUCP (Jean-Francois Lamy) writes:
> 
> Is there an easy way to have csh foreach loops that don't complain if the
> pattern given does not match any file...., 
> 

You might try:

touch dummy.tfm
foreach font (*.tfm)
    if $font = "dummy.dfm" continue
    set fontname = `basename $font .tfm`
    foreach size ($fontname.*pxl)
    ...
    end
end
rm dummy.tfm

-- 

David I. Berg (dberg)
Advanced Technology, Inc.
San Diego, CA

MILNET: dberg@nosc
UUCP:   {ihnp4 akgua decvax dcdwest ucbvax}!sdcsvax!noscvax!dberg