Parse command-line arguments: Difference between revisions

Added a possible Powershell version that doesn't use the built-in CmdLet Parser.
(Added FreeBASIC)
(Added a possible Powershell version that doesn't use the built-in CmdLet Parser.)
Line 375:
 
In addition to the above mechanism, the command line can also be handled "manually", by either processing the list of arguments returned by '[http://software-lab.de/doc/refA.html#argv argv]', or by fetching arguments individually with '[http://software-lab.de/doc/refO.html#opt opt]'.
 
=={{header|PowerShell}}==
Powershell functions and filters handle options organically, with advanced .NET support to handle complex and advanced options including aliases, ranges, sets, datatypes, and more. [https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.core/about/about_parsing See] [https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Functions more] [https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.core/about/about_functions_advanced here]. However, to parse options 'classically', you can write a custom parser. A slightly messy version (inspired by ruby optparse) that can only handle switches and relies on RegEx:
<lang Powershell>
$options = @{
opt1 = [bool] 0
opt2 = [bool] 0
opt3 = [bool] 0
}
$help = @"
FUNCTION usage: FUNCTION [-p] [-w] [-h] [-c] <int><float><string>PARAMETERS...
Lorem Ipsum blah blah blah
NOTE something yada yada
Options:
-p,--pxx Name Some option that has significance with the letter 'p'
-w,--wxx Name Some option that has significance with the letter 'w'
-c,--cxx Name Some option that has significance with the letter 'c'
-h,--help Help Prints this message
"@
 
function parseOptions ($argv,$options) {
$opts = @()
if (!$argv) { return $null }
foreach ($arg in $argv) {
# Make sure the argument is something you are expecting
$test = ($arg -is [int]) -or
($arg -is [string]) -or
($arg -is [float])
if (!$test) {
Write-Host "Bad argument: $arg is not an integer, float, nor string." -ForegroundColor Red
throw "Error: Bad Argument"
}
if ($arg -like '-*') { $opts += $arg }
}
$argv = [Collections.ArrayList]$argv
if ($opts) {
foreach ($opt in $opts) {
switch ($opt) {
{'-p' -or '--pxx'} { $options.opt1 = [bool] 1 }
{'-w' -or '--wxx'} { $options.opt2 = [bool] 1 }
{'-c' -or '--cxx'} { $options.opt3 = [bool] 1 }
{'-h' -or '--help'} { Write-Host $help -ForegroundColor Cyan; break 1 }
default {
Write-Host "Bad option: $arg is not a valid option." -ForegroundColor Red
throw "Error: Bad Option"
}
}
$argv.Remove($opt)
}
}
return [array]$argv,$options
}#fn
</lang>
Usage (in some function or script):
<lang Powershell>
begin {
$argv,$options = parseOptions $args $options
}
 
process {
if ($options.opt3) {
$foo = $blah - ($yada * $options.opt1) + ($yada * $options.opt2)
$bar = $argv | SomeOtherFilter | Baz
}
}
</lang>
 
WARNING: This is reinventing the wheel to an extreme degree.
 
=={{header|Racket}}==
Anonymous user