perl脚本中使用eval函数执行可能有异常的操作

perl脚本中有时候执行的操作可能会引发异常,为了直观的说明,这里举一个json反序列化的例子,脚本如下:

#! /usr/bin/perl
use v5.14;
use JSON;
use Data::Dumper;# 读取json字符串数据
my $json_str = join('', <DATA>);
# 反序列化操作
my $json = from_json($json_str);say to_json($json, { pretty => 1 });__DATA__
bad {"id" : 1024,"desc" : "hello world","other" : {"test_null" : null,"test_false" : false,"test_true" : true}
}

在这里插入图片描述

脚本中有意把正确json字符串之前加了几个字符,显然这个json字符串是不符合规范格式的,在git bash中执行这个脚本,结果如下:
在这里插入图片描述

下面用perl的eval函数改造这个脚本:

#! /usr/bin/perl
use v5.14;
use JSON;
use Data::Dumper;# 读取json字符串数据
my $json_str = join('', <DATA>);
# 反序列化操作
my $json = eval {return from_json($json_str);
};unless (defined $json) {say "from_json failed !!!!";
} else {say to_json($json, { pretty => 1 });
}__DATA__
bad {"id" : 1024,"desc" : "hello world","other" : {"test_null" : null,"test_false" : false,"test_true" : true}
}

脚本中用把from_json的操作放在eval函数中,输出结果如下:
在这里插入图片描述
显然,这个结果是可控的,可预期的。比如就可以使用这种方法判断json字符串是否合法,能够正常反序列化的就是合法的,否则就是非法的。eval函数的具体使用可以使用perldoc -f eval查看。

    eval EXPReval BLOCKeval    "eval" in all its forms is used to execute a little Perlprogram, trapping any errors encountered so they don't crash thecalling program.Plain "eval" with no argument is just "eval EXPR", where theexpression is understood to be contained in $_. Thus there areonly two real "eval" forms; the one with an EXPR is often called"string eval". In a string eval, the value of the expression(which is itself determined within scalar context) is firstparsed, and if there were no errors, executed as a block withinthe lexical context of the current Perl program. This form istypically used to delay parsing and subsequent execution of thetext of EXPR until run time. Note that the value is parsed everytime the "eval" executes.The other form is called "block eval". It is less general thanstring eval, but the code within the BLOCK is parsed only once(at the same time the code surrounding the "eval" itself wasparsed) and executed within the context of the current Perlprogram. This form is typically used to trap exceptions moreefficiently than the first, while also providing the benefit ofchecking the code within BLOCK at compile time. BLOCK is parsedand compiled just once. Since errors are trapped, it often isused to check if a given feature is available.In both forms, the value returned is the value of the lastexpression evaluated inside the mini-program; a return statementmay also be used, just as with subroutines. The expressionproviding the return value is evaluated in void, scalar, or listcontext, depending on the context of the "eval" itself. See"wantarray" for more on how the evaluation context can bedetermined.If there is a syntax error or runtime error, or a "die"statement is executed, "eval" returns "undef" in scalar context,or an empty list in list context, and $@ is set to the errormessage. (Prior to 5.16, a bug caused "undef" to be returned inlist context for syntax errors, but not for runtime errors.) Ifthere was no error, $@ is set to the empty string. A controlflow operator like "last" or "goto" can bypass the setting of$@. Beware that using "eval" neither silences Perl from printingwarnings to STDERR, nor does it stuff the text of warningmessages into $@. To do either of those, you have to use the$SIG{__WARN__} facility, or turn off warnings inside the BLOCKor EXPR using "no warnings 'all'". See "warn", perlvar, andwarnings.Note that, because "eval" traps otherwise-fatal errors, it isuseful for determining whether a particular feature (such as"socket" or "symlink") is implemented. It is also Perl'sexception-trapping mechanism, where the "die" operator is usedto raise exceptions.Before Perl 5.14, the assignment to $@ occurred beforerestoration of localized variables, which means that for yourcode to run on older versions, a temporary is required if youwant to mask some, but not all errors:# alter $@ on nefarious repugnancy only{my $e;{local $@; # protect existing $@eval { test_repugnancy() };# $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only$@ =~ /nefarious/ and $e = $@;}die $e if defined $e}There are some different considerations for each form:String evalSince the return value of EXPR is executed as a block withinthe lexical context of the current Perl program, any outerlexical variables are visible to it, and any packagevariable settings or subroutine and format definitionsremain afterwards.Under the "unicode_eval" featureIf this feature is enabled (which is the default under a"use 5.16" or higher declaration), EXPR is considered tobe in the same encoding as the surrounding program. Thusif "use utf8" is in effect, the string will be treatedas being UTF-8 encoded. Otherwise, the string isconsidered to be a sequence of independent bytes. Bytesthat correspond to ASCII-range code points will havetheir normal meanings for operators in the string. Thetreatment of the other bytes depends on if the"'unicode_strings"" feature is in effect.In a plain "eval" without an EXPR argument, being in"use utf8" or not is irrelevant; the UTF-8ness of $_itself determines the behavior.Any "use utf8" or "no utf8" declarations within thestring have no effect, and source filters are forbidden.("unicode_strings", however, can appear within thestring.) See also the "evalbytes" operator, which worksproperly with source filters.Variables defined outside the "eval" and used inside itretain their original UTF-8ness. Everything inside thestring follows the normal rules for a Perl program withthe given state of "use utf8".Outside the "unicode_eval" featureIn this case, the behavior is problematic and is not soeasily described. Here are two bugs that cannot easilybe fixed without breaking existing programs:*   It can lose track of whether something should beencoded as UTF-8 or not.*   Source filters activated within "eval" leak out intowhichever file scope is currently being compiled. Togive an example with the CPAN moduleSemi::Semicolons:BEGIN { eval "use Semi::Semicolons; # not filtered" }# filtered here!"evalbytes" fixes that to work the way one wouldexpect:use feature "evalbytes";BEGIN { evalbytes "use Semi::Semicolons; # filtered" }# not filteredProblems can arise if the string expands a scalar containinga floating point number. That scalar can expand to letters,such as "NaN" or "Infinity"; or, within the scope of a "uselocale", the decimal point character may be something otherthan a dot (such as a comma). None of these are likely toparse as you are likely expecting.You should be especially careful to remember what's beinglooked at when:eval $x;        # CASE 1eval "$x";      # CASE 2eval '$x';      # CASE 3eval { $x };    # CASE 4eval "\$$x++";  # CASE 5$$x++;          # CASE 6Cases 1 and 2 above behave identically: they run the codecontained in the variable $x. (Although case 2 hasmisleading double quotes making the reader wonder what elsemight be happening (nothing is).) Cases 3 and 4 likewisebehave in the same way: they run the code '$x', which doesnothing but return the value of $x. (Case 4 is preferred forpurely visual reasons, but it also has the advantage ofcompiling at compile-time instead of at run-time.) Case 5 isa place where normally you *would* like to use doublequotes, except that in this particular situation, you canjust use symbolic references instead, as in case 6.An "eval ''" executed within a subroutine defined in the"DB" package doesn't see the usual surrounding lexicalscope, but rather the scope of the first non-DB piece ofcode that called it. You don't normally need to worry aboutthis unless you are writing a Perl debugger.The final semicolon, if any, may be omitted from the valueof EXPR.Block evalIf the code to be executed doesn't vary, you may use theeval-BLOCK form to trap run-time errors without incurringthe penalty of recompiling each time. The error, if any, isstill returned in $@. Examples:# make divide-by-zero nonfataleval { $answer = $a / $b; }; warn $@ if $@;# same thing, but less efficienteval '$answer = $a / $b'; warn $@ if $@;# a compile-time erroreval { $answer = }; # WRONG# a run-time erroreval '$answer =';   # sets $@If you want to trap errors when loading an XS module, someproblems with the binary interface (such as Perl versionskew) may be fatal even with "eval" unless$ENV{PERL_DL_NONLAZY} is set. See perlrun.Using the "eval {}" form as an exception trap in librariesdoes have some issues. Due to the current arguably brokenstate of "__DIE__" hooks, you may wish not to trigger any"__DIE__" hooks that user code may have installed. You canuse the "local $SIG{__DIE__}" construct for this purpose, asthis example shows:# a private exception trap for divide-by-zeroeval { local $SIG{'__DIE__'}; $answer = $a / $b; };warn $@ if $@;This is especially significant, given that "__DIE__" hookscan call "die" again, which has the effect of changing theirerror messages:# __DIE__ hooks may modify error messages{local $SIG{'__DIE__'} =sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };eval { die "foo lives here" };print $@ if $@;                # prints "bar lives here"}Because this promotes action at a distance, thiscounterintuitive behavior may be fixed in a future release."eval BLOCK" does *not* count as a loop, so the loop controlstatements "next", "last", or "redo" cannot be used to leaveor restart the block.The final semicolon, if any, may be omitted from within theBLOCK.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/217374.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

《地理信息系统原理》笔记/期末复习资料(12. 地理信息工程)

目录 12. 地理信息工程 12.1. 地理信息系统工程的概念 12.2. 地理信息系统工程建设过程 12.2.1. 应用型地理信息系统设计步骤和方法 12.2.2. 需求分析 12.2.3. 系统设计 12.2.4. 系统开发与实施 12.2.5. 系统的评价和维护 12.3. GIS标准 12.4. 习题 12. 地理信息工程…

CNN、LeNet、AlexNet基于MNIST数据集进行训练和测试,并可视化对比结果

完成内容&#xff1a; 构建CNN并基于MNIST数据集进行训练和测试构建LeNet并基于MNIST数据集进行训练和测试构建AlexNet并基于MNIST数据集进行训练和测试对比了不同网络在MNIST数据集上训练的效果 准备工作 import torch import torch.nn as nn import torch.optim as optim …

高通SDX12:nand flash适配

一、SBL阶段 代码流程如下: boot_images\core\storage\flash\src\dal\flash_nand_init.c nand_probe ->nand_intialize_primary_hal_device ->>nand_get_device_list_supportedboot_images\core\storage\flash\src\dal\flash_nand_config.c ->>>flash_n…

ue4 解决角度万向锁的问题 蓝图节点

问题&#xff1a;当角度值从359-1变化的时候&#xff0c;数值会经历358、357… 解决方法&#xff1a;勾上Shortest Path&#xff0c;角度值的会从359-1

Kubernetes实战(十三)-使用kube-bench检测Kubernetes集群安全

1 概述 在当今云原生应用的开发中&#xff0c;Kubernetes已经成为标准&#xff0c;然而&#xff0c;随着其使用的普及&#xff0c;也带来了安全问题的挑战。本文将介绍如何使用kube-bench工具来评估和增强Kubernetes集群的安全性。 2 CIS (Center for Internet Security)简介…

OneCode低代码引擎 V2.0源码结构详解

前言 OneCode今天&#xff08;12月10日&#xff09;正式更新了其V2.0版本。从OneCode的季度版本生命中&#xff0c;可以看到2.0版本还是一个重量级的版本&#xff0c;笔者在收到2.0更新后第一时间下拉了最新的代码。在参考了OneCode 的技术说明后&#xff0c;根据包结构来分析…

MySQL笔记-第16章_变量、流程控制与游标

视频链接&#xff1a;【MySQL数据库入门到大牛&#xff0c;mysql安装到优化&#xff0c;百科全书级&#xff0c;全网天花板】 文章目录 第16章_变量、流程控制与游标1. 变量1.1 系统变量1.1.1 系统变量分类1.1.2 查看系统变量 1.2 用户变量1.2.1 用户变量分类1.2.2 会话用户变量…

GoLang EASY 微服务游戏框架 01

1 Overview EASY 是一个go语言编写的框架&#xff0c;兼容性支持go版本1.19&#xff0c;go mod 方式构建管理。它是一个轻型&#xff0c;灵活&#xff0c;自定义适配强的微服务框架。 它支持多种网络协议TCP&#xff0c;websocket&#xff0c;UDP&#xff08;待完成&#xf…

数据可视化:解析跨行业普及之道

数据可视化作为一种强大的工具&#xff0c;在众多行业中得到了广泛的应用&#xff0c;其价值和优势不断被发掘和利用。今天就让我以这些年来可视化设计的经验&#xff0c;讨论一下数据可视化在各个行业中备受青睐的原因吧。 无论是商业、科学、医疗保健、金融还是教育领域&…

蚂蚁SEO的百度蜘蛛池有哪些优势

一、介绍 SEO是搜索引擎优化&#xff08;Search Engine Optimization&#xff09;的缩写&#xff0c;是一种通过优化网站结构、内容和链接等元素&#xff0c;提高网站在搜索引擎中的排名&#xff0c;从而增加网站流量和吸引更多潜在客户的方法。SEO已成为现代网站管理的重要策…

聚观早报 |一加12首销;华为智能手表释放科技温暖

【聚观365】12月12日消息 一加12首销 华为智能手表释放科技温暖 卡尔动力获地平线战略投资 英伟达希望在越南建立基地 努比亚Z60 Ultra影像规格揭晓 一加12首销 现在有最新消息&#xff0c;近日一加12该机已于昨日开售&#xff0c;售价4299元起。 外观方面&#xff0c;全…

IDC报告:国内游戏云市场,腾讯云用量规模位列第一

12月12日消息&#xff0c;IDC公布最新的《中国游戏云市场跟踪研究&#xff0c;2022H2》报告&#xff08;以下简称“《报告》”&#xff09;显示&#xff0c;腾讯云凭借全球化节点布局以及国际领先的游戏技术积累&#xff0c;在整体规模、云游戏流路数、CDN流量峰值带宽等多维度…

“未来医疗揭秘:机器学习+多组学数据,开启生物医学新纪元“

在当今的数字化时代&#xff0c;科技正在不断地改变着我们的生活&#xff0c;同时也为医疗领域带来了巨大的变革。随着机器学习的快速发展&#xff0c;以及多组学数据在生物医学中的应用&#xff0c;我们正开启一个全新的医疗纪元。这个纪元以精准诊断、个性化治疗和高效康复为…

Docker容器:Centos7搭建Docker镜像私服harbor

目录 1、安装docker 1.1、前置条件 1.2、查看当前操作系统的内核版本 1.3、卸载旧版本(可选) 1.4、安装需要的软件包 1.5、设置yum安装源 1.6、查看docker可用版本 1.7、安装docker 1.8、开启docker服务 1.9、安装阿里云镜像加速器 1.10、设置docker开机自启 2、安…

K8S(一)—安装部署

目录 安装部署前提以下的操作指导(在master)之前都是三台机器都需要执行 安装docker服务下面的操作仅在k8smaster执行 安装部署 前提 以下的操作指导(在master)之前都是三台机器都需要执行 关闭防火墙 [rootk8smaster ~]# vim /etc/selinux/config [rootk8smaster ~]# swa…

指针浅谈(三)

在指针浅谈(二)http://t.csdnimg.cn/SKAkD中我们讲到了const修饰指针、指针运算、野指针、assert断言和传址调用的内容&#xff0c;今天我们继续学习有关数组名、指针访问数组、一维数组传参的本质相关的内容&#xff0c;内容比较深入&#xff0c;如果觉得哪里讲解的不行&#…

Docker部署Nacos集群并用nginx反向代理负载均衡

首先找到Nacos官网给的Github仓库&#xff0c;里面有docker compose可以快速启动Nacos集群。 文章目录 一. 脚本概况二. 自定义修改1. example/cluster-hostname.yaml2. example/.env3. env/mysql.env4. env/nacos-hostname.env 三、运行四、nginx反向代理&#xff0c;负载均衡…

【JavaEE学习】初识进程概念

个人主页&#xff1a;兜里有颗棉花糖 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 兜里有颗棉花糖 原创 收录于专栏【Java系列】【JaveEE学习专栏】 本专栏旨在分享学习JavaEE的一点学习心得&#xff0c;欢迎大家在评论区交流讨论&#x1f48c; 目录 一、…

python:五种算法(GA、OOA、DBO、SSA、PSO)求解23个测试函数(python代码)

一、五种算法简介 1、遗传算法GA 2、鱼鹰优化算法OOA 3、蜣螂优化算法DBO 4、麻雀搜索算法SSA 5、粒子群优化算法PSO 二、5种算法求解23个函数 &#xff08;1&#xff09;23个函数简介 参考文献&#xff1a; [1] Yao X, Liu Y, Lin G M. Evolutionary programming made…

百度文库下载要用券?Kotlin爬虫几步解决

百度作为国内知名的网站&#xff0c;尤其是文库里面有各种丰富的内容&#xff0c;对我们学习生活都有很大的帮助&#xff0c;就因为其内容丰富&#xff0c;如果看见好用有意思的文章还用复制粘贴等方式就显得有点落后了&#xff0c;今天我将用我所学的爬虫知识给你们好好上一课…