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

Fwd: more splitting travails



This was sent privately to me but pretty obviously intended for the list.

---------- Forwarded message ---------
From: Mark J. Reed <markjreed@xxxxxxxxx>
Date: Fri, Jan 12, 2024, 11:54 AM
Subject: Re: more splitting travails
To: Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx>


We talked offlist about how zsh inherited the paradoxical-looking and "${array[@]}" from earlier shells,  though it works differently such that a simple $array usually does what you want? 

Well, here's where the exception to that "usually" comes in.

Although the elements of an array expanded as simply $array don't get generally re-split on whitespace the way an unquoted ${array[@]} or ${array[*]} does in bash, any elements that are completely empty do get lost:

        zsh% array=(one two '' '' five )
    zsh% echo $#array
    5
    zsh% printf '%s\n' $array # King Arthur, is that you?
    one
    two
    five
    zsh% 

So that's where you need the wonky inherited syntax if you want to include empty values:

    zsh% printf '%s\n' "${array[@]}"
    one
    two
    
    
    five
    zsh%

Bart's question is also salient, however:

    > I have a file with blank lines in it, I read it into a variable

How do you read it in, and into what kind of variable? If you want to read a file into an array of lines, preserving empty lines, you can do this:

    lines=("${(@f)$(<~"$filename")}")

 The stuff in parentheses just inside the ${ are parameter expansion flags, which you can read about on the zshexpn man page.  In particular, the f flag splits the value on newlines, while the @ flag does the same thing as "${array[@]}" (which could therefore also be written as "${(@)array}"), but also works in other kinds of expansions, such as $(<filename) used here (which means  "get the contents of the file").

On Fri, Jan 12, 2024 at 2:19 PM Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
On Fri, Jan 12, 2024 at 11:05 AM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
>
> There's nothing harder than really getting on top of splitting issues :(
>
> I have a file with blank lines in it, I read it into a variable

This is probably the place you're getting messed up.  HOW do you read
it into a variable?

> Other various attempts give me the number of elements being the
> character count.  Weirdly there's places where I iterate over all the
> lines in 'List' and it *counts* nine, but only displays five.

Here you've probably done an earlier step right, but are forgetting to
quote what you're passing to print (or whatever "display" means).  The
default for arrays on the command line is to remove empty elements
unless quoted.



--
Mark J. Reed <markjreed@xxxxxxxxx>


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