Thursday, August 24, 2023

Foreach Derp with Csh

Foreach derp with Csh

Type-less shells like Bourne Shell, or Csh, are always confusing me. In the later case, there technically aren’t numbers (floats: no, no, no), and data structures are more or less limited to word lists, and arrays.

With Csh, I’m perennially tripped up when I have a word list in Csh, whereby I confuse it for an array, when it isn’t (or vise versa). And this isn’t helped by the fact that this construct:

foreach ( args )

… actually has more going on in Csh than I originally thought. Or maybe, has less going on… not sure.

To be clear, while loops, if statements, etc., all use parentheses the way other langs use them — as a way to compartmentalize the arguments.

But in the case of Csh’s ‘foreach …’ Hold the phone.

Globals

In Unix, globals, or globs, are a way to expand file listing with the use of wildcards. There are a few flavors of wildcards, but for the sake of this post, I’ll just use the splat (*).

So, for instance, when we want to ‘cat’ some files that all end in ‘.txt,’ this glob yields a word list (in the case of Csh).

cat *.txt >& /dev/null

To see this word list more clearly, this is illuminating:

echo *

And you’ll see, what’s yielded is an actual… word… list.

Coercing, sorta

If you want to iterate on a word list, then you can throw it into some parentheses, turning it into an array:

set us = ( * )

And that’s incidentally what the ‘foreach’ construct in Csh does.

(And where I’m constantly being tripped up.)

Rather than thinking of the parentheses as a corner to hold your args, in Csh, the mandatory parentheses do that, but also mutates your word list into an array (Thank you? Csh?).

Now, most languages don’t have their parentheses coming after them like that. Lisp, maybe… But with Csh, we all know it’s a little bit, special.



from Hacker News https://ift.tt/XTlp3xb

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.