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

推荐订阅源

The GitHub Blog
The GitHub Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Y
Y Combinator Blog
B
Blog RSS Feed
K
Kaspersky official blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Know Your Adversary
Know Your Adversary
C
CERT Recently Published Vulnerability Notes
V
Vulnerabilities – Threatpost
C
Check Point Blog
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
Spread Privacy
Spread Privacy
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Hacker News
The Hacker News
P
Palo Alto Networks Blog
L
Lohrmann on Cybersecurity
T
Tor Project blog
T
Tenable Blog
H
Help Net Security
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
S
Schneier on Security
G
Google Developers Blog
P
Privacy & Cybersecurity Law Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
Microsoft Azure Blog
Microsoft Azure Blog
Cyberwarzone
Cyberwarzone
Security Latest
Security Latest
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
美团技术团队
博客园 - 三生石上(FineUI控件)
Latest news
Latest news
腾讯CDC
G
GRAHAM CLULEY
阮一峰的网络日志
阮一峰的网络日志
博客园 - 叶小钗
博客园 - 【当耐特】
C
CXSECURITY Database RSS Feed - CXSecurity.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
Martin Fowler
Martin Fowler

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
A "switch" for Perl that compiles away: introducing Switch::Declare
LNATION · 2026-06-14 · via DEV Community

Perl has had a complicated relationship with switch.

given/when arrived leaning on smartmatch, and smartmatch turned out to be a pit of surprising behaviour — so the whole feature was been experimental, then discouraged, then warned-about for years. Switch::Back.pm is given/when for a post-given/when Perl then there is the old Switch.pm that reached for a source filter, which means it rewrites your program text before Perl ever sees it; and then finally there are a handful of other implementations on cpan including my own Switch::Again.

So most of us generally just write if/elsif chains and move on. They're honest and fast, but they're also noisy: the scrutinee gets repeated on every branch, and a six way string dispatch turns into six eq comparisons stacked on top of each other.

Switch::Declare is an attempt to get the nice syntax without any of the historical baggage. The pitch in one line:

a real switch/case keyword that is parsed entirely at compile time,
scoped lexically like a proper pragma, and lowered to the same op tree
no source filter, no smartmatch, no runtime dependencies.

use Switch::Declare;

switch ($value) {
    case 200           { handle_ok()    }   # numeric   -> ==
    case "GET"         { handle_get()   }   # string    -> eq
    case /^\d+$/       { all_digits()   }   # regex     -> =~
    case [400 .. 499]  { client_error() }   # range     -> >= && <=
    case ["a","b","c"] { in_set()       }   # list      -> membership
    case \&is_weekend  { weekend()      }   # predicate -> $code->($topic)
    default            { fallback()     }
}

It's an expression, too

The construct yields the value of the arm that ran, so you can use it on the right hand side of an assignment instead of mutating a variable in each branch:

my $label = switch ($status) {
    case 200 { "ok" }
    case 404 { "missing" }
    default  { "other" }
};

The scrutinee — $status here — is evaluated exactly once. The first matching case wins, there is no implicit fall-through, and a trailing default catches everything else. As an expression with no match and no default, you get undef.

The patterns are a small, predictable grammar

Rather than try to be clever, case recognises a deliberately tiny set of literal pattern shapes, and each one lowers to the cheapest operator that does the job:

Pattern Example Becomes
number literal case 200 numeric ==
string literal case "GET" string eq
regex case /^\d+$/ $topic =~ /.../
range [LO .. HI] case [400..499] inclusive bounds
list [a, b, c] case [1, 2, 3] membership (OR)
predicate case \&is_even $code->($topic)

The predicate form takes either a code reference (\&name, package-qualified names work too) or an inline sub { ... } that closes over the surrounding lexicals, which is the escape hatch for anything the literal grammar deliberately doesn't cover:

my $limit = 100;
switch ($n) {
    case sub { $_[0] > $limit } { "over" }
    default                     { "ok"   }
}

Because the grammar is literals rather than arbitrary expressions,
classification is never ambiguous, and the compiler always knows exactly which operator to emit.

Why "compile-time" matters for speed

This is the part I'm most pleased with. switch is installed through Perl's core keyword-plugin and lexer APIs. When the parser reaches the keyword, the module reads the whole construct, builds an op tree for it then and there, and hands that back in place of the keyword. After compilation, nothing of the parser remains — there is no dispatcher subroutine sitting between you and your code at runtime, no per-call wrapper, no closure to invoke.

For the common case — a plain variable or constant scrutinee with
single-expression arms — switch compiles to exactly a hand-written if/elsif (ternary) chain: no temporary, no extra scope, no extra ops. In the bundled benchmark (xt/bench.pl) the two run within measurement noise of each other (0–2%).

Dispatch mode: O(n) chain → O(1) lookup

There's a nice bonus. When a switch is effectively a lookup table, every case maps a string literal to a constant value, and there are at least a handful of arms the module quietly lowers it to a single hash lookup against a table built once at compile time, instead of walking a chain of eq tests:

# compiles to one hash lookup, not six string comparisons
my $name = switch ($code) {
    case "GET"    { "read"   }
    case "PUT"    { "update" }
    case "POST"   { "create" }
    case "DELETE" { "remove" }
    case "PATCH"  { "modify" }
    case "HEAD"   { "peek"   }
    default       { "?"      }
};

In the benchmark, a 20-arm string switch in dispatch mode runs about 2.5× faster than the equivalent if/elsif chain. You never opt in or out, it's chosen automatically, and it never changes behaviour.

A real lexical pragma

The switch keyword only exists inside the lexical scope of a
use Switch::Declare, and you can turn it off again with no Switch::Declare:

{
    use Switch::Declare;
    switch ($x) { ... }   # 'switch' is the keyword here
}

switch();                 # ...and an ordinary sub call out here

Outside that scope, switch is just an identifier. So the keyword can't collide with a switch function in unrelated code, and importing the module has no spooky action at a distance.

Benchmarking

Numbers help. As I mentioned years ago I wrote
Switch::Again, which solves the same problem from the opposite end: switch LIST builds a closure at run time that matches each call's argument against its keys (via Struct::Match).

Here is the same 20-way string dispatch written both ways:

# Switch::Declare — parsed once at compile time, lowered to a hash lookup
my $n = switch ($key) {
    case "k0" { 0 } case "k1" { 1 } ... case "k19" { 19 }
    default   { -1 }
};

# Switch::Again — dispatcher closure built once, then called
my $sw = switch
    k0  => sub { 0 },
    k1  => sub { 1 },
    ...
    k19 => sub { 19 },
    default => sub { -1 };
my $n = $sw->($key);

The benchmark builds the Switch::Again dispatcher once,
outside the timed loop, so we're comparing steady-state per-call cost — the fairest possible footing for a runtime matcher. Results on perl 5.42:

== 6 string arms (Switch::Declare chain mode) ==
                      Rate   Switch::Again        if/elsif Switch::Declare
Switch::Again     411555/s              --            -97%            -98%
if/elsif        13282260/s           3127%              --            -33%
Switch::Declare 19891605/s           4733%             50%              --

== 20 string arms (Switch::Declare dispatch mode -> hash lookup) ==
                      Rate   Switch::Again  hand %dispatch Switch::Declare
Switch::Again     183089/s              --            -98%            -99%
hand %dispatch  11888675/s           6393%              --            -40%
Switch::Declare 19837923/s          10735%             67%              --

== 3 regex arms ==
                     Rate   Switch::Again Switch::Declare
Switch::Again   1233188/s              --            -82%
Switch::Declare 6736915/s            446%              --

So at six string arms Switch::Declare is about 48× faster than Switch::Again; at twenty arms, where dispatch mode kicks in, it's about 108× faster — and still 67% faster than a hand rolled %dispatch table, because it returns the matched constant straight out of the hash instead of calling a coderef per hit. Even on regexes, where there's no hash trick to play, it's about 5.5× ahead.

Getting it

cpanm Switch::Declare

Give it a try, and let me know how it goes in the comment section below.