Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Slurping a file (was: more spllitting travails)



2024-02-10 22:46:15 -0600, Bart Schaefer:
> On Sat, Feb 10, 2024 at 2:48 PM Stephane Chazelas <stephane@xxxxxxxxxxxx> wrote:
> >
> > IMO, it would be more useful if the result was returned in the
> > variable whose name was given as argument (defaulting to REPLY
> > if none was given like for read or sysread).
> 
> Could also read a file provided by name as an argument instead of only
> reading stdin, but I elected to commit the most straightforward
> version.

Yes, using redirection as in:

zslurp a < file1
zslurp b < file2

is easy enough

> 
> > And would be better if upon error the returned variable
> > contained either what was successfully read or nothing (like
> > read but unlikely sysread).
> 
> I had the impression this slurp-er was intended to work like examples
> from other languages, which do not have "read"-like behavior.

It sounded safer to me to avoid leaving the variable unmodified
if the input could not be read in case the caller forgets to do
error handling, but then again in

zslurp a < file1

above, if file1 cannot be opened, zslurp won't be called so $a
will be left unmodified regardless (same in read var < file1),
so yes, probably pointless.

> 
> > zslurp() {
> >   emulate -L zsh -o no_multibyte
> >   typeset -n _zslurp_var=${1-REPLY}
> 
> Is there really any reason to prefix the locals with "_zslurp_" ?
> That's good practice if the function might call other code that's less
> careful about it's names and scoping, or if you need to the variable
> to become global, but nothing like that occurs here.

See https://zsh.org/workers/52530
From my quick testing I had assumed zsh's nameref worked like
bash ones and were just a lexical dereferencing, hence the
namespacing. But it seems that is only needed in cases where
referenced variables were not declared in the caller. If
workers/52530 is addressed, that namespacing is no longer
needed.

-- 
Stephane




Messages sorted by: Reverse Date, Date, Thread, Author