How to query the number of arguments passed to a CLI program?

I am trying to find a way to query the number of arguments passed to a Julia CLI program.

This is what I have come up with, but it doesn’t quite make sense. (Explanation below.)

function main()

    if size(ARGS) != 1
        println("Error: Invalid number of arguments, expected 1 arguments DATE")
        println("there were $(size(ARGS)) args")
        println(typeof(size(ARGS)))
        println(typeof(ARGS))
    end

    target_date::Union{Date, Nothing} = nothing

    for arg in ARGS
        println("arg: $(arg)")
        date::Date = Date(arg, dateformat"yyyymmdd")
        println("Running for date $(date)")
        target_date = date
    end
end

main()

This doesn’t work because size(ARGS) returns a Tuple{Int64}. Here’s the output:

there were (1,) args
Tuple{Int64}
Vector{String}

I find this surprising since a list of arguments passed to a CLI program can only be 1 dimensional. This is imposed by the Operating System, since it represents those arguments as an array of pointers to character strings.

I can of course “fix it” by simply taking the first element of the tuple before performing the comparison with the if statement. However, this feels like bad software engineering practice, because if I were to try to access size(ARGS)[1], usually one should first check that this element exists. (In other words, check that size did not return an empty vector.)

But that is a lot of arguably unnecessary additional work.

Does anyone have any thoughts about this?

you want length(ARGS)

2 Likes

Ah of course, that makes sense. Thanks