Why you cannot use an argument that starts with a number?


This is a quick, one Act drama about how the past defines the present.

Exposition

I recently had the requirement to create a PowerShell script and was planning to use parameters that begin with a number. Something like this

function MyFunction
{
    param
    (
        [int]$5turns
    )
    Write-Host $5turns
} 

This turned out to be a bad idea. I got a dirty error message when calling my function:

MyFunction: Cannot process argument transformation on parameter '5turns'. Cannot convert value "-5turns" to type "System.Int32". Error: "Input string was not in a correct format."

Act 1

I was surprised to see that finding an answer is not that easy. No matter which search engine I used, all of them offered results that explained how argument conversion works. Finally I found a loooong thread that explained that coders sometime are lazy, and this is the cause of the problem. Imagine the following declaration:

int a = 1
int 2a = 3
int b = 2a

Should b be equal to 2 or should it be 3?

Well... As you can see, this is pure laziness, as we assume 2a actually means two times a, which could be represented as 2*a.

Now, let's assume I understand that it would be confusing in certain languages, but in PowerShell 2$a should never be considered as $2a.

 

Dénouement

Moral of the story: pay attention to the programming techniques prof. Or if you did not attend such seminars (like myself), remember, that using a parameter beginning with a number is not an option. Ehh...

Comments (0)

Skip to main content