Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Square Brackets in Switch Command 1

Status
Not open for further replies.

mvvilleza

MIS
Nov 23, 2000
114
PH
Hi all,

Can i use square brackets with the switch command? Eg.

$a=5
switch($a)
{
[1-9]{$a="0"+$a}
}
$a

My desired output is 05.
 
You can't do it directly, but you can use expressions for comparisons so the following works:
Code:
switch ($a)
{
   {($_ -ge 1) -and ($_ -le 9)} {$a = "0" + $a}
}
 
Just out of curiosity, are you trying to write code to zero pad or some other way format strings? If so, there are probably existing commands to do that for you.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Just as a quick example, if you wanted to 0 pad a number out to 2 digits:

$a = 5
"{0:0#}" -f $a

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Thanks crobin1, your solution is great.

To EBGreen,

You are correct, i'm trying to add a 0 to a single digit number from 1 to 9. i just assigned 5 in $a, if you notice the question is about square brackets in a switch command.
 
I understood the question, and crobin1 had already provided a good answer. I was just suggesting an alternate solution to what you were trying to do.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top