惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - Franky
U
Unit 42
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
量子位
博客园 - 【当耐特】
罗磊的独立博客
B
Blog
Stack Overflow Blog
Stack Overflow Blog
F
Fortinet All Blogs
爱范儿
爱范儿
The Cloudflare Blog
Engineering at Meta
Engineering at Meta
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
Apple Machine Learning Research
Apple Machine Learning Research
N
Netflix TechBlog - Medium
Google DeepMind News
Google DeepMind News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
H
Help Net Security
S
SegmentFault 最新的问题
aimingoo的专栏
aimingoo的专栏
B
Blog RSS Feed
L
LangChain Blog
T
Tailwind CSS Blog
WordPress大学
WordPress大学
GbyAI
GbyAI
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
Vercel News
Vercel News
Recent Announcements
Recent Announcements
博客园 - 司徒正美
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cybersecurity and Infrastructure Security Agency CISA
L
LINUX DO - 热门话题
Security Latest
Security Latest
T
Threat Research - Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Beautiful Perl feature: low-precedence boolean operators 'and', 'or'
Laurent Dami · 2026-05-09 · via DEV Community

Beautiful Perl series

This post is part of the beautiful Perl features series. See the introduction post for general explanations about the series.

Today's feature is quite unique in programming languages: the fact that Perl has two different syntaxes for expressing the same boolean operations. Read on to understand why this is clever and beautiful.

Boolean algebra and short-circuit evaluation

The basic operations of Boolean algebra are fundamental in programming; therefore they are present in all programming languages. In the C language, later followed by many other languages, icluding Perl, logical conjunction (the "AND" operator) is written &&, logical disjunction (the "OR" operator) is written ||, and logical negation (the "NOT" operator) is written !. Conjunction has higher precedence than disjunction, so a && b || c && d is parsed as (a && b) || (c && d) and not a && (b || c) && d. The unary negation operator has even higher precedence.

Mathematically speaking, both AND and OR operators are commutative : the left and right operands can be switched without affecting the result. But in programming languages the order of operands is not totally indifferent, because operands have an evaluation cost; therefore the system usually spares the cost of evaluating the right operand whenever it has enough information from the left operand to compute the result of the boolean operation: this is called short-circuit evaluation. For example in the conjunction $x < 9999 && is_prime($x), if $x is a large number, the left condition is false, so the whole expression is necessarily false and there is no need to do an expensive computation to decide if the number is prime. Similarly, when the left operand of a disjunction is true, then the whole expression is true and the right operand need not be evaluated.

Short-circuit evaluation is not only a question of performance: it also has important consequences when operand expressions have side-effects, like changing the value of a global variable or interacting with files, sockets or other elements of the operating system. Because of short-circuiting, the value of the left operand determines if the side-effects of the right operand will happen or not. In languages of C lineage, many common idioms take advantage of this feature for avoiding runtime exceptions: conditions checked in the left operand must be met before operations in the right operand are attempted. For example the left condition might be to check if a file is present before attempting to open it, or check if a number is different from zero before using it as denominator in a division. Here is a C example borrowed from Wikipedia:

bool isFirstCharValidAlpha(const char* p) {
    return p != NULL && isalpha(p[0]); // 1) no unneeded isalpha() execution
                                       //    with p == NULL,
                                       // 2) no SEGFAULT risk
}

Enter fullscreen mode Exit fullscreen mode

Perl expressions are also statements

In languages other than Perl, examples of boolean expressions where operands have side-effects are not frequent, apart from the family of idioms just mentioned. Expressions with side-effects may even be considered inadvisable. Perl is different, because expressions are also statements, as explained in perlsyn:

The only kind of simple statement is an expression evaluated for its side-effects.

Therefore a boolean combination of expressions is also a statement. Likewise, instructions in real life may also be combinations of more atomic instructions:

Add four spoons of sugar and dissolve it into the preparation, or replace it by honey.

The above sentence indeed can be seen as a boolean expression with short-circuit: either you add sugar and then you must dissolve it and there is no need for honey, or you don't use sugar, so there is no need to dissolve anything, and you just have to incorporate the honey.

This way of expressing composite instructions is used everyday in natural language; therefore, expressing programming instructions in a similar way helps to make them easily understandable by humans, often better than sequences of if-then-else constructs, at least when the composite instruction only contains two or three individual clauses. Most programming languages would require the individual clauses to be enclosed in parentheses, which impedes readability.

Boolean expressions in Perl: two sets of operators, same semantics, different precedence

Perl's brilliant solution for improving the readability of composite instructions is to offer another set of boolean operators, written as the English words and, or, not, with exactly the same semantics as the usual &&, || and !, but with lower precedence. Actually, these word versions of boolean operators have the lowest precedence of all in Perl's table of operators, which means that statements between such keywords will be nicely parsed as an individual clauses. Let us look at a simple example:

say "tic", "tac" and say "toe";

Enter fullscreen mode Exit fullscreen mode

The intended result is two lines of output

tictac
toe

Enter fullscreen mode Exit fullscreen mode

and it indeed works that way. The first say is a list operator of very high precedence. Commas after such an operator build a list that will be fed as arguments to say ... but that list stops at the keyword and because of its very low precedence, so it is equivalent to the following parenthesized version:

say("tic", "tac") and say("toe");

Enter fullscreen mode Exit fullscreen mode

Now since we are using parentheses, we might as well write

say("tic", "tac") && say("toe");

Enter fullscreen mode Exit fullscreen mode

with exactly the same result. By contrast, the && version without parentheses

say "tic", "tac" && say "toe"

Enter fullscreen mode Exit fullscreen mode

produces a different output:

toe
tic1

Enter fullscreen mode Exit fullscreen mode

because everything after the first say was treated as an argument list to that say, so an equivalent parenthesized version would be:

say("tic", ("tac" && say("toe")));

Enter fullscreen mode Exit fullscreen mode

The expression "tac" && say "toe" needs to be evaluated first, which is why the output has toe on the first line. The result of that expression is 1 because since the left operand is true, the boolean && returns the value of the right operand say("toe"), which is 1. Then the outer say can do its job, and since it received two arguments "tic" and 1, it prints tic1 on the second line.

This example with say was good for explanations, but is unlikely to be written like this in real programs. More realistic situations involve other list operators, like this very common idiom with open:

open my $fh, '<', $filename
  or die "failed to open '$filename': $!";

Enter fullscreen mode Exit fullscreen mode

Here is another example with mkdir; this also shows that of course several successive boolean connectors can be combined:

-d $dir                                # does this directory exist ?
  or mkdir $dir                        # if not, try to create it
  or die "failed to mkdir '$dir': $!"; # if the creation failed, report the error

Enter fullscreen mode Exit fullscreen mode

Assignment operations

Examples so far were mainly with the or operator. Usage of and is more often combined with assignment operations: a variable takes the value of an expression, and if that value is not empty, then a follow-up operation is performed.

$n_items = $aref && @$aref
  and say "this array contains $n_items items"
  or  say "this array is empty";

Enter fullscreen mode Exit fullscreen mode

This example assumes a variable $aref to be a reference to an array. The first line checks if the reference is indeed defined, and if so, if it refers to a non-empty array. Depending on the result, the appropriate follow-up message is printed.

For this example to work, the $n_items variable must be already declared earlier in the code: unfortunately it wouldn't work here to write my $n_items = ... because the my declaration would only take effect at the end of the whole statement; therefore at the point where the interpreter parses the string "this array contains $n_items items", variable $n_items would not be declared yet and would throw an exception.

This excerpt shows a single expression containing both && and and. Perl's table of operator precedence has been carefully crafted so that the assignment operator = (and its derivatives +=, *=, etc.) has lower precedence than boolean operators in their symbolic syntax &&, || or !, but higher precedence than those operators in their english syntax and, or, not. Therefore the value assigned to $n_items is $aref && @$aref, including the && operator, but it does not include what comes after the and.

The result of a boolean operator is the last operand

The example of the previous section assigns a boolean expression to a variable $n_items whose name indicates that it is not meant to receive a constant true or false but an integer number! This may be surprising for readers accustomed to strongly typed languages like Java or C++, where the result of a boolean expression can only take one of two boolean values.

By contrast, boolean expressions in Perl, like in several other dynamically typed languages (JavaScript, Python, Ruby, etc.), return the the last evaluated value. That value therefore can have a dual purpose: not only can it be tested for truthness (where any value different from undef, 0, "0" or "" means "true"), but it can also be used for its regular scalar value, as a number, string or reference. Many common idioms in Perl and other similar languages take advantage of this feature for writing compact expressions. A more verbose but more explicit version of the assignment above would be:

$n_items = defined $aref ? @$aref > 0 ? @$aref
                                      : 0
                         :              undef;

Enter fullscreen mode Exit fullscreen mode

Real example

To conclude with a real example, here is an excerpt from my module Data::Domain with quite heavy use of idiomatic and / or constructs:

sub _inspect {
  my ($self, $data) = @_;

  looks_like_number($data)
    or return $self->msg(INVALID => $data);

  if (defined $self->{-min}) {
    $data >= $self->{-min}
      or return $self->msg(TOO_SMALL => $self->{-min});
  }
  if (defined $self->{-max}) {
    $data <= $self->{-max}
      or return $self->msg(TOO_BIG => $self->{-max});
  }
  if (defined $self->{-not_in}) {
    grep {$data == $_} @{$self->{-not_in}}
      and return $self->msg(EXCLUSION_SET => $data);
  }

  return;
}

Enter fullscreen mode Exit fullscreen mode

Like always in Perl, there are several ways to do it. Here the stylistic choice was to use if statements for checking the main conditions, but and / or expressions for secondary checks. Another way to write the condition on -min could be:

  defined $self->{-min}
    and $data < $self->{-min}
    and return $self->msg(TOO_SMALL => $self->{-min});

Enter fullscreen mode Exit fullscreen mode

or perhaps

  return $self->msg(TOO_SMALL => $self->{-min})
    if defined $self->{-min} and $data < $self->{-min};

Enter fullscreen mode Exit fullscreen mode

Low precedence and/or in other programming languages

Apart from Perl, dual sets of boolean operators are only found in Ruby and PHP, two programming languages that were heavily influenced by Perl. Apparently their designers considered that this was a good idea! By contrast, a language like Python where the motto is there is only one way to do it did not adopt such a design.

Apart from stylistic preferences, the reason why low-precedence boolean operators in Perl are so effective is that they combine especially well with the other features of the language mentioned above, like the fact that expressions are also instructions, and the fact that boolean expressions return the last evaluated value.

Conclusion

Perl's invention of a double set of operators for a same purpose was a bold step, clearly on a different path than usual endeavors in programming language design that often seek to minimize the set of operators, with features as orthogonal as possible.

Yet Perl's choice integrates particularly well with other technical features of the language and with its general philosophy. Algorithmic steps can be written in a way that closely reflects natural language and natural thinking, without heavy syntactic if-then-else constructs and without verbose parentheses.

About the cover picture

Since the seminal Camel Book, Perl has been associated with the image of a camel (actually a dromedary). Here we have a camel carrying a performing organist ... nice illustration for a beautiful Perl feature. This woodcut print is part of a 16th-century Triumphal Procession series commissioned by the Holy Roman Emperor Maximilian I. The image is borrowed from the Deutsch Fotothek.