转换为“是"或“否"布尔值 [英] convert "Yes" or "No" to boolean

查看:138
本文介绍了转换为“是"或“否"布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析.CSV文件中包含的用户值.我不希望我的用户输入是"或否",而是输入真"或假".在每种情况下,我都想转换为等效的布尔值:$true$false.理想情况下,我想要一个默认值,因此如果拼写错误是或否",我将返回我的默认值:$true$false.

I want to parse user values contained in .CSV file. I don't want my users to enter "Yes" or "No" but instead enter "True" or "False". In each case I want to convert to the equivalent boolean values: $true or $false. Ideally I would like a default value, so if there's misspelt "Yes or "No" I would return my default value: $true or $false.

因此,我想知道是否有除此以外的整洁方法

Hence, I wondered if there is a neat way of doing this other than

if(){} else (){}

推荐答案

一种方法是switch语句:

$bool = switch ($string) {
  'yes' { $true }
  'no'  { $false }
}

如果要处理既不是是"也不是否"的值,请添加子句default:

Add a clause default if you want to handle values that are neither "yes" nor "no":

$bool = switch ($string) {
  'yes'   { $true }
  'no'    { $false }
  default { 'neither yes nor no' }
}

另一个选择可能是简单的比较:

Another option might be a simple comparison:

$string -eq 'yes'            # matches just "yes"

$string -match '^y(es)?$'    # matches "y" or "yes"

如果字符串匹配,这些表达式的计算结果为$true,否则为$false.

These expressions would evaluate to $true if the string is matched, otherwise to $false.

这篇关于转换为“是"或“否"布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆