zsh-users
 help / color / mirror / code / Atom feed
* Use of left- and right-padding with a variable padding char
@ 2021-07-24  7:47 Zach Riggle
  2021-07-24 10:08 ` Mikael Magnusson
  0 siblings, 1 reply; 2+ messages in thread
From: Zach Riggle @ 2021-07-24  7:47 UTC (permalink / raw)
  To: zsh-users

As always, thank you all so much for your time.  It's genuinely appreciated.

I want to define a function "center", which takes $1="Some String" and
$2="-" or some other default padding value.

The Zsh manual on expansion says that I can do something like this,
which works well and as intended:

    function center() {
        local text="${1:-hellworld}"
        local -i columns=${COLUMNS:-$(tput cols)}
        columns=$(( columns/2 ))
        echo ${(l:${columns}::=:::r:${columns}::=:::)text}
    }

This works very well, and correctly centers "${text}" across the width
of the terminal, with "=" padding on both sides.  Perfect.

However, I also want to make the padding character ("=" in the above
example) be variable.

The following does NOT work as intended, and I'm not sure why.  My
understanding is that variable expansion is inside-out, so it SHOULD
work.

    function center() {
        local text="${1:-hellworld}"
        local pad="${2:-=}"
        local -i columns=${COLUMNS:-$(tput cols)}
        columns=$(( columns/2 ))
        echo ${(l:${columns}::${pad}:::r:${columns}::${pad}:::)text}
    }
    center "hello" "_"

The value in $1 is correctly centered, but it is padded with the
LITERAL value '${pad}', rather than the expansion of ${pad}.

I expect there's some documentation that I haven't read yet, any tips
would be useful.

Zach Riggle


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2021-07-24 10:10 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2021-07-24  7:47 Use of left- and right-padding with a variable padding char Zach Riggle
2021-07-24 10:08 ` Mikael Magnusson

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).