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.rhkb.cn/news/217605.html

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

相关文章

linux 应用开发笔记---【信号:基础】

1.基本概念 信号是发生事件时对进程的通知机制&#xff0c;也可以称为软件中断 信号的目的是用来通信的 1.硬件发生异常&#xff0c;将错误信息通知给内核&#xff0c;然后内核将相关的信号给相关的进程 2.在终端输入特殊字符产生特殊信号 3.进程调用kill()将任意信号发送…

开发人员必须掌握的几个高级命令

xargs命令 在平时的使用中,我认为 xargs 这个命令还是较为重要和方便的。我们可以通过使用这个命令,将命令输出的结果作为参数传递给另一个命令。 比如说我们想找出某个路径下以 .conf 结尾的文件,并将这些文件进行分类,那么普通的做法就是先将以 .conf 结尾的文件先找出…

逆向获取某音乐软件的加密(js逆向)

本文仅用于技术交流&#xff0c;不得以危害或者是侵犯他人利益为目的使用文中介绍的代码模块&#xff0c;若有侵权请联系作者更改。 老套路&#xff0c;打开开发者工具&#xff0c;直接开始找到需要的数据位置&#xff0c;然后观察参数&#xff0c;请求头&#xff0c;cookie是…

GitHub Universe 2023 Watch Party in Shanghai:在开源世界中找到真我

文章目录 ⭐ 前言⭐ “我”的开源之旅⭐ 为什么要做开源⭐ 要如何做好开源⭐ 开源的深度影响⭐ 小结 ⭐ 前言 周末有幸参加了在上海举行的 GitHub Universe 2023 Watch Party&#xff0c;这是一个充满激情和活力的开源开发者日。我有幸聆听了一场特别令人印象深刻的演讲&#…

“注我“合作伙伴or竞品分析。# 持续更新

"注我"的定位 合作或者竞品介绍 请问分析一个科技产品竞品的时候应该带着什么思维、问题、角度、框架或者系统去问&#xff1f; 在分析科技产品的竞品时&#xff0c;以下思维、问题、角度、框架或系统可能会有所帮助&#xff1a; 思维&#xff1a; 竞争思维&…

【c++随笔16】reserve之后,使用std::copy会崩溃?

【c随笔16】reserve之后&#xff0c;使用std::copy会崩溃? 一、reserve之后&#xff0c;使用std::copy会崩溃?二、函数std::reserve、std::resize、std::copy1、std::resize&#xff1a;2、std::reserve&#xff1a;3、std::copy&#xff1a; 三、崩溃原因分析方案1、你可以使…

Windows下使用CMake编译lua

Lua 是一个功能强大、高效、轻量级、可嵌入的脚本语言。它支持程序编程、面向对象程序设计、函数式编程、数据驱动编程和数据描述。 Lua的官方网站上只提供了源码&#xff0c;需要使用Make进行编译&#xff0c;具体的编译方法为 curl -R -O http://www.lua.org/ftp/lua-5.4.6.…

GAN的原理分析与实例

为了便于理解&#xff0c;可以先玩一玩这个网站&#xff1a;GAN Lab: Play with Generative Adversarial Networks in Your Browser! GAN的本质&#xff1a;枯叶蝶和鸟。生成器的目标&#xff1a;让枯叶蝶进化&#xff0c;变得像枯叶&#xff0c;不被鸟准确识别。判别器的目标&…

vim + ctags 跳转, 查看函数定义

yum install ctags Package ctags-5.8-13.el7.x86_64 already installed and latest version 创建 /home/mzh/pptp-master/tags.sh #!/usr/bin/shWORKDIR/home/mzh/pptp-masterfind ${WORKDIR} -name "*.[c|h]" | xargs ctags -f ${WORKDIR}/tags find /usr/inclu…

排序算法:【冒泡排序】、逻辑运算符not用法、解释if not tag:

注意&#xff1a; 1、排序&#xff1a;将一组无序序列&#xff0c;调整为有序的序列。所谓有序&#xff0c;就是说&#xff0c;要么升序要么降序。 2、列表排序&#xff1a;将无序列表变成有序列表。 3、列表这个类里&#xff0c;内置排序方法&#xff1a;sort( )&#xff0…

大数据讲课笔记1.4 进程管理

文章目录 零、学习目标一、导入新课二、新课讲解&#xff08;一&#xff09;进程概述1、基本概念2、三维度看待进程3、引入多道编程模型&#xff08;1&#xff09;CPU利用率与进程数关系&#xff08;2&#xff09;从三个视角看多进程 4、进程的产生和消亡&#xff08;1&#xf…

平台工程与 DevOps 和 SRE 有何不同?

在现代软件开发和运营的动态领域中 &#xff0c;平台工程、DevOps 和站点可靠性工程 (SRE) 等术语 经常使用&#xff0c;有时可以互换使用&#xff0c;这常常会导致进入或浏览这些领域的专业人员感到困惑。了解这些概念之间的细微差别对于努力构建强大且可扩展的系统的组织至关…

爱智EdgerOS之深入解析安全可靠的开放协议SDDC

一、协议简介 在 EdgerOS 的智慧生态场景中&#xff0c;许多智能设备或传感器的生命周期都与 SDDC 协议息息相关&#xff0c;这些设备可能是使用 libsddc 智能配网技术开发的&#xff0c;也有可能是因为主要功能上是使用其他技术如 MQTT、LoRa 等但是设备的上下线依然是使用上…

构建外卖小程序:技术代码实践

在这个数字化的时代&#xff0c;外卖小程序已经成为餐饮业的一项重要工具。在本文中&#xff0c;我们将通过一些简单而实用的技术代码&#xff0c;向您展示如何构建一个基本的外卖小程序。我们将使用微信小程序平台作为例子&#xff0c;但这些原理同样适用于其他小程序平台。 …

连连看游戏

连通块记忆性递归的综合运用 这里x&#xff0c;y的设置反我平常的习惯&#xff0c;搞得我有点晕 实际上可以一输入就交换x&#xff0c;y的数据的 如果设置y1为全局变量的话会warning&#xff1a; warning: built-in function y1 declared as non-function 所以我改成p和q了…

阿里云人工智能平台PAI多篇论文入选EMNLP 2023

近期&#xff0c;阿里云人工智能平台PAI主导的多篇论文在EMNLP2023上入选。EMNLP是人工智能自然语言处理领域的顶级国际会议&#xff0c;聚焦于自然语言处理技术在各个应用场景的学术研究&#xff0c;尤其重视自然语言处理的实证研究。该会议曾推动了预训练语言模型、文本挖掘、…

Bytebase 2.12.0 - 改进自动补全和布局导航

&#x1f680; 新功能 支持 MySQL 高级自动补全。支持从 UI 上导入分类分级配置。 &#x1f514; 重大变更 作废已有企业版试用证书。之后可以通过提交申请获取新的试用证书。 &#x1f384; 改进 改进整体布局和导航。 支持在 SQL 编辑器里显示以及查询 PostgreSQL 数据…

HCIA-H12-811题目解析(9)

1、【单选题】下面选项中&#xff0c;能使一台IP地址为10.0.0.1的主机访问Interne的必要技术是&#xff1f; 2、【单选题】 FTP协议控制平面使用的端口号为&#xff1f; 3、【单选题】 使用FTP进行文件传输时&#xff0c;会建立多少个TCP连接&#xff1f; 4、【单选题】完成…

【算法Hot100系列】寻找两个正序数组的中位数

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

WordPress主题Lolimeow v8.0.1二次元风格支持erphpdown付费下载

WordPress国人原创动漫主题lolimeow免费下载 lolimeow是一款WordPress国人原创主题&#xff0c;风格属于二次元、动漫、可爱萝莉风&#xff0c;带有后台设置&#xff0c;支持会员中心。该主题为免费主题。 1.侧栏/无侧栏切换&#xff01; 2.会员中心&#xff08;配套Erphpdown…