7.3 Foreach loops

Foreach loops may be used to run a script block once for each item in a list or dictionary. Alternatively, if a string is supplied, it is treated as a filename wildcard, and all matching files are returned. For example:

foreach x in [-1,pi,10]
 { print x ; }

foreach x in "*.dat"
 { print x ; }

myDict = { 'a':1 , 'b':2 }
foreach x in myDict
 { print x ; }

The first of these loops would iterate three times, with the variable x holding the values $-1$, $\pi $ and $10$ in turn. The second of these loops would search for any data files in the user’s current directory with filenames ending in .dat and iterate for each of them. As previously, the wildcard character * matches any string of characters, and the character ? matches any single character. Thus, foo?.dat would match foo1.dat and fooX.dat, but not foo.dat or foo10.dat. The effect of the print statement in this particular example would be rather similar to typing:

!ls *.dat

An error is returned if there are no files in the present directory which match the supplied wildcard. The following example would produce plots of all of the data files in the current directory with filenames foo_*.dat or bar_*.dat as eps files with matching filenames:

set terminal eps
foreach x in "foo_*.dat" "bar_*.dat"
  outfilename =  x
  outfilename =~ s/dat/eps/
  set output outfilename
  plot x using 1:2

If a dictionary is supplied to loop over, then the loop variable iterates over each of the keys in the dictionary.