• Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)

Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.  

Decision Making Statements in Perl :

  • If – else
  • Nested – If
  • if – elsif ladder
  • Unless – else
  • Unless – elsif  

if statement

The if statement is same as in other programming languages. It is used to perform basic condition based task. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. Syntax :

Note : If the curly brackets { } are not used with if statements then there will be compile time error. So it is must to use the brackets { } with if statement. Flowchart :  

perl if statement variable assignment

Example :  

Output :  

if – else Statement

The if statement evaluates the code if the condition is true but what if the condition is not true, here comes the else statement. It tells the code what to do when the if condition is false. Syntax :

Flowchart :  

perl if statement variable assignment

Nested – if Statement

if statement inside an if statement is known as nested if. if statement in this case is the target of another if or else statement. When more than one condition needs to be true and one of the condition is the sub-condition of parent condition, nested if can be used. Syntax :  

Flowchart :    

perl if statement variable assignment

 

If – elsif – else ladder Statement

Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that get executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. Syntax :  

if-else-if

unless Statement

In this case if the condition is false then the statements will execute. The number 0, the empty string “”, character ‘0’, the empty list (), and undef are all false in a boolean context and all other values are true. Syntax :

perl if statement variable assignment

Unless-else Statement

Unless statement can be followed by an optional else statement, which executes when the boolean expression is true. Syntax :

perl if statement variable assignment

Output :   

Unless – elsif Statement

Unless statement can be followed by an optional elsif…else statement, which is very useful to test the various conditions using single unless…elsif statement. Points to Remember :  

  • Unless statement can have zero to many elsif’s and all that must come before the else.
  • Unless statement can have zero or one else’s and that must come after any elsif’s.
  • Once an elsif succeeds, then none of remaining elsif’s or else’s will be tested.

perl if statement variable assignment

   

author

Please Login to comment...

Similar reads.

  • perl-basics
  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

ProgramGuru.org

  • ➤ Perl Tutorials
  • ➤ Perl Else If Statement

Perl Tutorials

  • ✓ Hello World Program
  • ✓ Basic Syntax
  • ✓ Variables
  • ✓ If Statement
  • ✓ If-Else Statement
  • ✓ Else If Statement
  • ✓ While Loop
  • ✓ Break Statement
  • ✓ Next Statement

Perl How-Tos

  • ✓ Strings How-Tos
  • ✓ Arithmetic Operations How-Tos
  • ✓ Comparison Operations How-Tos
  • ✓ Pattern Printing How-Tos
  • ✓ Arrays How-Tos
  • ✓ Sets How-Tos

Perl Else If Statement

In this tutorial, we will learn about else-if statements in Perl. We will cover the basics of conditional execution using if-else-if statements.

What is an Else-If statement

An else-if statement is a conditional statement that allows multiple conditions to be tested sequentially. It provides a way to execute different code blocks based on different conditions.

The syntax for the else-if statement in Perl is:

The else-if statement evaluates the specified conditions in order. The first condition that is true will have its code block executed; if none of the conditions are true, the code block inside the else statement is executed.

Flowchart of Else-If Statement

Checking if a Number is Positive, Negative, or Zero

  • Declare a variable num .
  • Assign a value to num .
  • Use an if-else-if statement to check if num is positive, negative, or zero.
  • Print a message indicating whether num is positive, negative, or zero.

Perl Program

Checking the grade of a student.

  • Declare a variable marks .
  • Assign a value to marks .
  • Use an if-else-if statement to check the grade based on the marks .
  • Print a message indicating the grade.

Checking the Temperature Range

  • Declare a variable temperature .
  • Assign a value to temperature .
  • Use an if-else-if statement to check the range of the temperature .
  • Print a message indicating the temperature range.

© programguru.org 2024

perl if statement variable assignment

Conditional Decisions

Perl conditional statements allow conditions to be evaluated or tested with a statement or statements to be executed per the condition value which can be either true or false .

Perl does not have native boolean types. However, the numeric literal 0, the strings "0" and "", the empty array () and undef are all considered false in the context of condition evaluation.

Below are several types of conditional statements:

  • if (condition) statement
  • if (condition) {statement1; statement2; statement3;}
  • if (condition) statement else statement
  • if (condition) elsif (condition) statement else statement
  • unless (condition) statement
  • unless (condition) statement else statement
  • unless (condition) elsif (condition) statement else statement

Ternary operator

The ? conditional operator is a simplified method of if (condition) statement else statement . It has the general form of: (condition) ? statement1 : statement2 .

First the condition is evaluated. If true, then statement1 is executed and becomes the value of the expression, otherwise, statement2 is executed and becomes the value of the expression.

Equality and Comparison Operators

These operators can be used to define conditions in conditional statements. Numeric values and string values are compared using different operators

Numeric values operators

  • == true if the value of the left operand is equal to the value of right operand, else false
  • != true if the value of the left operand is not equal to the value of right operand, else false
  • ! negates the boolean value of whatever comes after this in a conditional expression
  • <=> Compares the values of two numeric values and returns -1, 0, or 1 if the left argument is numerically less than, equal to, or greater than the right argument, respectively
  • > true if the value of the left operand is smaller than the value of right operand, else false
  • < true if the value of the left operand is lower than the value of right operand, else false
  • >= true if the value of the left operand is smaller or equal than the value of right operand, else false
  • <= true if the value of the left operand is lower or equal than the value of right operand, else false

String values operators

  • eq true if the left argument is stringwise equal to the right argument
  • ne true if the left argument is stringwise not equal to the right argument
  • gt true if the left argument is stringwise greater than the right argument
  • lt true if the left argument is stringwise less than the right argument
  • ge true if the left argument is stringwise greater than or equal to the right argument
  • le true if the left argument is stringwise less than or equal to the right argument
  • cmp -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument, respectively

An array @family holds a list of family member names. The first hash %shoe_color contains favorite shoe color per person name. The second hash %shoe_size contains shoe size per person name.

Evaluate and print the favorite shoe color and shoe size per each family member. For shoe sizes 10 and above, add the word 'large' to the output line.

Output lines should be in the format: "Homer wears large brown shoes size 12".

Note : not all family members may be included in the hash variables, so you better conditionally check if they exist or not (using the exists operator). If a name does not exist, add the key/value pair into the hash variables - for show color add: black ; for shoe size add 99 .

perl if statement variable assignment

Coding for Kids is an online interactive tutorial that teaches your kids how to code while playing!

Receive a 50% discount code by using the promo code:

Start now and play the first chapter for free, without signing up.

perl if statement variable assignment

Popular Articles

  • Creating Characters By Code Point (Sep 09, 2024)
  • Interpolation Of Scalar Variables Into Strings (Sep 09, 2024)
  • Output With Print (Sep 09, 2024)
  • Compound Assignment Operators (Sep 09, 2024)
  • Scalar Assignment (Sep 09, 2024)

Perl If Else

Switch to English

Table of Contents

Introduction

Understanding perl's if-else statement, usage examples, elif statements, tips and tricks, common error-prone cases and how to avoid them.

  • The 'if-else' statement is a conditional construct that checks a specific condition and performs an action based on whether the condition is true or false. If the condition is true, it executes one block of code; if false, it executes another.
  • Here, 'condition' is an expression that returns either a true or false value. The 'if' keyword is followed by this condition enclosed within parentheses. After that, a block of code within curly braces {} is executed if the condition is true. If the condition is false, the code within the 'else' block is executed.
  • Let's consider a simple example where we want to check if a number is even or odd.
  • In this example, the condition '$num % 2 == 0' checks if the number is even. If it is, it prints "number is even"; otherwise, it prints "number is odd".
  • Perl also provides the 'elsif' keyword to add more conditions to your 'if-else' statement.
  • In this example, Perl checks each condition in order. If '$num' equals 1, it prints "One". If '$num' equals 2, it prints "Two". If '$num' is neither 1 nor 2, it prints "Number is not one or two".
  • Remember to always enclose the condition within parentheses. Forgetting the parentheses is a common mistake that can lead to syntax errors.
  • Use curly braces {} to define the 'if' and 'else' blocks. Code readability is critical, and braces enhance structure visibility.
  • Ensure conditions are logically correct. A common error is to use the assignment operator (=) instead of the equality operator (==) in the condition. While the former assigns a value, the latter checks for equality.
  • One common error is forgetting to use the 'elsif' keyword when adding more conditions. Using multiple 'if' statements instead of 'elsif' can lead to unexpected results as each 'if' statement is evaluated separately.
  • Another common mistake is not considering all possible cases in your conditions. For instance, if you're checking a variable that can have three possible values but only account for two in your 'if-else' statement, your code may fail to handle the third case properly. Always ensure that your conditions cover all possible scenarios.

alvin alexander

Perl if, else, elsif ("else if") syntax

Summary: This tutorial shows a collection of Perl if , else , and else if examples.

Here are some examples of the Perl if/else syntax, including the “else if” syntax, which is really elsif . (I wrote this because after working with many different languages I can never remember the “else if” syntax for most languages, and elsif is pretty rare.)

The Perl if/else syntax

The Perl if / else syntax is standard, I don’t have any problems here:

The Perl “else if” syntax (elsif)

The Perl “else if” syntax actually uses the elsif keyword. Here’s some example code that show this syntax:

Perl’s numeric and string comparison operators

While I’m in the neighborhood of Perl and equality/comparison tests, here’s a list of Perl’s numeric and string comparison/equality operators:

Not knowing the Perl has different operators for numeric tests and string tests can be a big “gotcha” when programming in Perl (so I wanted to make sure I noted this here).

Help keep this website running!

  • Perl comparison operators
  • Perl ‘equals’ FAQ: What is true and false in Perl?
  • Perl file test operators (reference)
  • How to use the Perl ternary operator
  • The Perl unless operator

books by alvin

  • My free Scala 3 and Functional Programming video courses
  • Star Wars: Rogue One: Demonstrating mantra meditation at its best
  • Christian voter/voting, swing states, and misinformation: What to do
  • Dear Fellow 2024 Christian Voters: Trust The Bible, Jesus, and yourself
  • Highly-rated Functional Programming book
No such thing as a small change
  
by (Acolyte) ) NODE.title = Assignment to a value only if it is defined NODE.owner = 818413 N.title = monktitlebar sitedoclet N.owner = 17342 -->
( = : , )
has asked for the wisdom of the Perl Monks concerning the following question:

This is fine unless $bar is a complex statement or a function that I don't want to call twice. Of course I could create a temporary variable which makes the code even uglier:

What I would like is a short and simple syntax where I only have to type each part of the conditional assignment once:

Any ideas? The code should be short and readable. Bonus points if $foo can also be a list.

Assignment to a value only if it is defined or Code
Replies are listed 'Best First'.

by (Monsignor) on Jan 20, 2010 at 12:01 UTC

Or just do what the others said above (5.10+ only):




by (Acolyte) on Jan 20, 2010 at 15:44 UTC

However this is not much better then

Because the other part of the statement ($foo) is duplicated - if I have a long variable like $myhash{mykey}->{mykey2} instead of $foo it only gets uglier. I was looking for a simple and short syntax like:

But appereantly such operator does not exist in Perl. The best solution I found so far (also ugly but not getting more complex if $foo and $bar are long expressions) is:




by (Paladin) on Jan 20, 2010 at 16:40 UTC

Then try:



by (Patriarch) on Jan 20, 2010 at 19:02 UTC



by (Patriarch) on Jan 20, 2010 at 19:01 UTC

The preceeding solution is very similar to what you asked ( ) and very simple (single op).

I'm not sure if you mean or

: Added second and third.




by (Acolyte) on Jan 21, 2010 at 16:48 UTC

And in case of a list I'll use the (slightly less readable) 'for grep defined,' psuedo-inline operator. It only makes sense with list references (if you treat (undef) as valid list). Defined scalar values which are transformed to a list can also be handled:




by (Patriarch) on Jan 20, 2010 at 10:40 UTC
:




by (Canon) on Jan 20, 2010 at 10:56 UTC
What the OP wants is: which is equivalent to assuming the absence of ties and overloading.


by (Canon) on Jan 20, 2010 at 10:48 UTC
would test if is defined, not (it's equivalent to ).




by (Hermit) on Jan 20, 2010 at 18:27 UTC

Back to Seekers of Perl Wisdom

Password:

www . com | www . net | www . org

  • GrandFather
  • Seekers of Perl Wisdom
  • Cool Uses for Perl
  • Meditations
  • PerlMonks Discussion
  • Categorized Q&A
  • Obfuscated Code
  • Perl Poetry
  • PerlMonks FAQ
  • Guide to the Monastery
  • What's New at PerlMonks
  • Voting/Experience System
  • Other Info Sources
  • Nodes You Wrote
  • My Watched Nodes
  • Super Search
  • List Nodes By Users
  • Newest Nodes
  • Recently Active Threads
  • Selected Best Nodes
  • Worst Nodes
  • Saints in our Book
  • Random Node
  • The St. Larry Wall Shrine
  • Offering Plate
  • Planet Perl
  • Perl Weekly
  • Perl Mongers
  • Perl documentation
-->
‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, .

Conditional Statements

When ever you want to perform a set of operations based on a condition(s) If / If-Else / Nested ifs are used.

You can also use if-else , nested IFs and IF-ELSE-IF ladder when multiple conditions are to be performed on a single variable.

Check result here

3. if-else-if ladder, 4. nested-if.

Nested-Ifs represents if block within another if block.

Unless is similar to If and is equivalent to if-not . Perl executes the code block if the condition evaluates to false, otherwise it skips the code block.

Check Result here

6. unless-else.

Given is similar to Switch in other programming languages. Given is an alternative to IF-ELSE-IF ladder and to select one among many blocks of code.

if-else Statement

Let's discuss if-else statements in detail, including nested-ifs with examples.

Branches in Perl

  • The if-else statement
  • Explanation
  • Nested if-statements

We often need the execution of some portions of our code to be subject to a certain condition(s). Within the Perl programming language, the simplest and sometimes the most useful way of creating a condition within your program is through an if-else statement.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy

Advanced Perl Maven

  • Installing and getting started with Perl
  • The Hash-bang line, or how to make a Perl scripts executable on Linux
  • Perl Editor
  • How to get Help for Perl?
  • Perl on the command line
  • Core Perl documentation and CPAN module documentation
  • POD - Plain Old Documentation
  • Debugging Perl scripts
  • Common Warnings and Error messages in Perl
  • Prompt, read from STDIN, read from the keyboard in Perl
  • Automatic string to number conversion or casting in Perl
  • Conditional statements, using if, else, elsif in Perl
  • Boolean values in Perl
  • Numerical operators
  • String operators: concatenation (.), repetition (x)
  • undef, the initial value and the defined function of Perl
  • Strings in Perl: quoted, interpolated and escaped
  • Here documents, or how to create multi-line strings in Perl
  • Scalar variables
  • Comparing scalars in Perl
  • String functions: length, lc, uc, index, substr
  • Number Guessing game
  • Scope of variables in Perl
  • Short-circuit in boolean expressions
  • How to exit from a Perl script?
  • Standard output, standard error and command line redirection
  • Warning when something goes wrong
  • What does die do?
  • Writing to files with Perl
  • Appending to files
  • Open and read from text files
  • Don't Open Files in the old way
  • Reading and writing binary files in Perl
  • EOF - End of file in Perl
  • tell how far have we read a file
  • seek - move the position in the filehandle in Perl
  • slurp mode - reading a file in one step
  • Perl for loop explained with examples
  • Perl Arrays
  • Processing command line arguments - @ARGV in Perl
  • How to process command line arguments in Perl using Getopt::Long
  • Advanced usage of Getopt::Long for accepting command line arguments
  • Perl split - to cut up a string into pieces
  • How to read a CSV file using Perl?
  • The year of 19100
  • Scalar and List context in Perl, the size of an array
  • Reading from a file in scalar and list context
  • STDIN in scalar and list context
  • Sorting arrays in Perl
  • Sorting mixed strings
  • Unique values in an array in Perl
  • Manipulating Perl arrays: shift, unshift, push, pop
  • Reverse Polish Calculator in Perl using a stack
  • Using a queue in Perl
  • Reverse an array, a string or a number
  • The ternary operator in Perl
  • Loop controls: next, last, continue, break
  • min, max, sum in Perl using List::Util
  • qw - quote word
  • Subroutines and functions in Perl
  • Passing multiple parameters to a function in Perl
  • Variable number of parameters in Perl subroutines
  • Returning multiple values or a list from a subroutine in Perl
  • Understanding recursive subroutines - traversing a directory tree
  • Hashes in Perl
  • Creating a hash from an array in Perl
  • Perl hash in scalar and list context
  • exists - check if a key exists in a hash
  • delete an element from a hash
  • How to sort a hash in Perl?
  • Count the frequency of words in text using Perl
  • Introduction to Regexes in Perl 5
  • Regex character classes
  • Regex: special character classes
  • Perl 5 Regex Quantifiers
  • trim - removing leading and trailing white spaces with Perl
  • Perl 5 Regex Cheat sheet
  • What are -e, -z, -s, -M, -A, -C, -r, -w, -x, -o, -f, -d , -l in Perl?
  • Current working directory in Perl (cwd, pwd)
  • Running external programs from Perl with system
  • qx or backticks - running external command and capturing the output
  • How to remove, copy or rename a file with Perl
  • Reading the content of a directory
  • Traversing the filesystem - using a queue
  • Download and install Perl
  • Installing a Perl Module from CPAN on Windows, Linux and Mac OSX
  • How to change @INC to find Perl modules in non-standard locations
  • How to add a relative directory to @INC
  • How to replace a string in a file with Perl
  • How to read an Excel file in Perl
  • How to create an Excel file with Perl?
  • Sending HTML e-mail using Email::Stuffer
  • Perl/CGI script with Apache2
  • JSON in Perl
  • Simple Database access using Perl DBI and SQL
  • Reading from LDAP in Perl using Net::LDAP
  • Global symbol requires explicit package name

Variable declaration in Perl

  • Use of uninitialized value
  • Barewords in Perl
  • Name "main::x" used only once: possible typo at ...
  • Unknown warnings category
  • Can't use string (...) as an HASH ref while "strict refs" in use at ...
  • Symbolic references in Perl
  • Can't locate ... in @INC
  • Scalar found where operator expected
  • "my" variable masks earlier declaration in same scope
  • Can't call method ... on unblessed reference
  • Argument ... isn't numeric in numeric ...
  • Can't locate object method "..." via package "1" (perhaps you forgot to load "1"?)
  • Useless use of hash element in void context
  • Useless use of private variable in void context
  • readline() on closed filehandle in Perl
  • Possible precedence issue with control flow operator
  • Scalar value ... better written as ...
  • substr outside of string at ...
  • Have exceeded the maximum number of attempts (1000) to open temp file/dir
  • Use of implicit split to @_ is deprecated ...
  • Multi dimensional arrays in Perl
  • Multi dimensional hashes in Perl
  • Minimal requirement to build a sane CPAN package
  • Statement modifiers: reversed if statements
  • What is autovivification?
  • Formatted printing in Perl using printf and sprintf
  • declaration

The trouble

The exceptions, the danger of the explicit package name, use warnings, always use strict.

Gabor Szabo

Published on 2013-07-23

Author: Gabor Szabo

perl if statement variable assignment

Home » Perl Variables

Perl Variables

Summary :  in this tutorial, you’ll learn about Perl variables , variable scopes, and variable interpolation.

To manipulate data in your program, you use variables.

Perl provides three types of variables: scalars, lists, and hashes to help you manipulate the corresponding data types including scalars, lists, and hashes .

You’ll focus on the scalar variable in this tutorial.

Naming variables

You use scalar variables to manipulate scalar data such as numbers and strings .

A scalar variable starts with a dollar sign ( $ ), followed by a letter or underscore, after that, any combination of numbers, letters, and underscores. The name of a variable can be up to 255 characters.

Perl is case-sensitive. The $variable and $Variable are different variables.

Perl uses the dollar sign ( $ ) as a prefix for the scalar variables because of the $  looks like the character S in the scalar. You use this tip to remember when you want to declare a scalar variable.

The following example illustrates valid variables:

However, the following variables are invalid in Perl.

Declaring variables

Perl doesn’t require you to declare a variable before using it.

For example, you can introduce a variable in your program and use it right away as follows:

In some cases, using a variable without declaring it explicitly may lead to problems. Let’s take a look at the following example:

The expected output was Your favorite color is red .  

However, in this case, you got Your favorite color is , because the $color and $colour are different variables. The mistake was made because of the different variable names.

To prevent such cases, Perl provides a pragma called strict that requires you to declare variable explicitly before using it. 

In this case, if you use the  my keyword to declare a variable and try to run the script, Perl will issue an error message indicating that a compilation error occurred due to the  $colour variable must be declared explicitly.

A variable declared with the  my keyword is a lexically scoped variable.

It means the variable is only accessible inside the enclosing block or all blocks nested inside the enclosing block. In other words, the variable is local to the enclosing block.

Now, you’ll learn a very important concept in programming called variable scopes.

Perl variable scopes

Let’s take a look at the following example:

In the example above:

  • First, declared a global variable named  $color .
  • Then, displayed the favorite color by referring to the $color variable. As expected, we get the red color in this case.
  • Next, created a new block and declared a variable with the same name $color using the my keyword. The  $color variable is lexical. It is a local variable and only visible inside the enclosing block.
  • After that, inside the block, we displayed the favorite color and we got the blue color. The local variable takes priority in this case.
  • Finally, following the block, we referred to the $color variable and Perl referred to the  $color global variable.

If you want to declare global variables that are visible throughout your program or from external packages, you can use our   keyword as shown in the following code:

Perl variable interpolation

Perl interpolates variables in double-quoted strings. It means if you place a variable inside a double-quoted string, you’ll get the value of the variable instead of its name.

Perl interpolates the value of $amount into the string which is 20.

Note that Perl only interpolates scalar variables and arrays , not hashes . In addition, the interpolation is only applied to the double-quoted string, but not the single-quoted string.

In this tutorial, you have learned about Perl variables including naming and declaring scalar variables. You’ve also learned about variable scopes and variable interpolation.

Perl Onion

  •   AUTHORS
  •   CATEGORIES
  • #   TAGS

Use the logical-or and defined-or operators to provide default subroutine variable behaviour

Jul 6, 2013 by David Farrell

Perl subroutines do not have signatures so variables must be initialized and arguments assigned to them inside the subroutine code. This article describes two useful shortcuts that can simplify this process.

One trick that Perl programmers use is the logical-or operator (‘||’) to provide default behaviour for subroutine arguments. The default behaviour will only occur if the argument is provided is false (undefined, zero or a zero-length string). Imagine that we’re developing a subroutine that processes data for car insurance quotes - we’ll need to collect some basic data such as the applicant’s date of birth, sex and number of years driving. All of the arguments are mandatory - we can use the logical-or operator to return early if these arguments are false.

What this subroutine code does is assign the first element of the default array (@_) to $args using shift. By default shift will operate on @_, so there is no need to include it as an argument. Next the subroutine initializes and assigns the $dob and $sex variables. In both cases we use the logical-or (‘||’) operator to return early from the subroutine if these variables are false. This is a more concise code pattern than using an if statement block. We cannot use this trick to return early from the $years_driving variable as it may be provided as zero, which Perl treats as logical false but we want to keep. So in this case we have to first check if the argument was defined (which would include zero) and then use a ternary operator to either assign the value or return early.

Since version 5.10.0 Perl has has had the defined-or operator (‘//’). This will check if the variable is defined, and if it is not, Perl will execute the code on the right-side of the operator. We can use it to simplify our subroutine code:

In the modified code above, first we have included a line to use Perl 5.10.0 or greater - this will ensure that the version of Perl executing the code has the defined-or operator. Next we’ve simplified the code for $years_driving to use the logical-or operator. This will now accept zero as an argument, but return when $years_driving is undefined.

Default values

We can also use defined-or to provide default values for subroutine arguments. For example if we assumed that all users of our subroutine are male, we can change the $sex variable to default to ’M’.

Now if the $sex variable is undef, the process_quote_data subroutine will assign ’M’ as it’s value.

You can read more about these operators and in the perlop section of the official Perl documentation.

This article was originally posted on PerlTricks.com .

David Farrell

David is a professional programmer who regularly tweets and blogs about code and the art of programming.

Browse their articles

Something wrong with this article? Help us out by opening an issue or pull request on GitHub

To get in touch, send an email to [email protected] , or submit an issue to tpf/perldotcom on GitHub.

This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 Unported License .

Creative Commons License

Perl.com and the authors make no representations with respect to the accuracy or completeness of the contents of all work on this website and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. The information published on this website may not be suitable for every situation. All work on this website is provided with the understanding that Perl.com and the authors are not engaged in rendering professional services. Neither Perl.com nor the authors shall be liable for damages arising herefrom.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

'if' after assignment

What is the following line supposed to do in Perl?

It looks like it adds ";" at the end of the key when it already exists. Is it true?

Is it different than putting the "if" statement before assigning?

  • if-statement

Peter Mortensen's user avatar

  • 1 You are right. And there is no difference. If you put the "if" in front you just have to put curly braces around the assignment. –  jpstrube Commented Mar 3, 2015 at 13:12
  • 1 Perl allows for post- if statements and also allows for post- while , and post- for loops too. However, these things are usually discouraged because people scanning the code may miss the if . Plus, if you realize you need to add another statement in the if , you have to rewrite the statement. –  David W. Commented Mar 3, 2015 at 13:23
  • @DavidW.: . . . and post- unless and post- until :) –  Borodin Commented Mar 3, 2015 at 13:28
  • One advantage is that it allows you to use fewer parentheses: $result{$key} .= ';' if exists $result{$key}; –  David W. Commented Mar 3, 2015 at 13:42
  • I would generally avoid post statements, but make exceptions for next unless or return if type constructs, because I consider the 'flow control' element important the more important one. –  Sobrique Commented Mar 3, 2015 at 13:43

5 Answers 5

Perl allows you to do conditional statements either before or after.

This is to allow you to do things like:

So yes, you're right - that's a conditional append in that if the key exists, it'll stick a semicolon on the end of the value . (As noted in comments - it does not change the key.)

It isn't any different to:

Generally, it's a style and maintainability question as to which you use. I would generally suggest avoiding it, because it generally makes things less clear. (But not always - see above for a couple of examples.)

Sobrique's user avatar

  • 5 The OP is strictly wrong when he says, “It looks like it adds ";" at the end of key when it already exists” as the semicolon is added at the end of the hash value . –  Borodin Commented Mar 3, 2015 at 13:33
  • The official term (at least in Programming Perl , p. 130 in one edition) for the post one is modifier ( statement modifier ?). –  Peter Mortensen Commented Apr 30, 2021 at 20:11

1) Could someone tell me what is this line supposed to do in perl:

Answer: The above expression can be read as

Explanation: if condition checks for existence of value obtained from the hash result( %result ) with the key as $key , If the value exists then append the semicolon to the end of the value.

2) It looks like it adds ";" at the end of key when it already exists, is it true?

NO, Semicolon will be added to the end of the value and not at the end of the key, when it(value) exists, as value for a key is obtained from hash via $hashName{$keyName}

3)Is it different than putting "if" statement before assigning?

No, It is not different, but an another way writing.

kvivek's user avatar

It's exactly as you said. It means:

If the hash %result has an element with key $key , append ; to the element's value.

is just another way of writing

ikegami's user avatar

can be written as:

There isn't any difference.

serenesat's user avatar

do exactly the same thing. There are times where you may prefer one over another for better readability.

rubikonx9's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged perl if-statement or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Bringing clarity to status tag usage on meta sites
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • What is the missing fifth of the missing fifths?
  • What is "boosted electrical level" in a USB?
  • Does plan guide consider spaces or not?
  • Getting lost on a Circular Track
  • traceroute (UDP) lost packets
  • I want to be a observational astronomer, but have no idea where to start
  • Model reduction in linear regression by stepwise elimination of predictors with "non-significant" coefficients
  • Mistake on car insurance policy about use of car (commuting/social)
  • Is the white man at the other side of the Joliba river a historically identifiable person?
  • Flats on gravel with GP5000 - what am I doing wrong?
  • How to go from Asia to America by ferry
  • "Vector Character" in Whitehead's Process and Reality
  • Switching x-axis and z-axis To appear instead of each other
  • Textile Innovations of Pachyderms: Clothing Type
  • `uname -r` shows kernel marked as `vmlinuz.old` in `/boot` partition
  • Could a lawyer agree not to take any further cases against a company?
  • Correct anonymization of submission using Latex
  • How do you make the vacuum seal on a glass jar?
  • How to raise and lower indices as a physicist would handle it?
  • Radial distribution of ideal gas in a cylinder
  • subtle racism in the lab
  • How cheap would rocket fuel have to be to make Mars colonization feasible (according to Musk)?
  • Could they free up a docking port on ISS by undocking the emergency vehicle and letting it float next to the station for a little while
  • How many color information loss if I iterate all hue and value while keep saturation constant?

perl if statement variable assignment

IMAGES

  1. Perl if statements

    perl if statement variable assignment

  2. Perl If Else Statements

    perl if statement variable assignment

  3. Perl if statements

    perl if statement variable assignment

  4. Perl else if

    perl if statement variable assignment

  5. Perl Basics: If/If Else/ElsIf Statements

    perl if statement variable assignment

  6. Perl else if

    perl if statement variable assignment

VIDEO

  1. _DSDV_Discuss Structure, Variable Assignment Statement in verilog

  2. Assignment Statement and Constant Variable

  3. 6 storing values in variable, assignment statement

  4. Chapter 1 Sample Program

  5. Beginner Perl Maven tutorial 4.2

  6. Perl Tutorials -Part 92

COMMENTS

  1. Perl

    Local identifiers in most languages, including Perl, are usually written using lower-case letters, digits, and the underscore _. Capital letters are reserved for global variables, and in Perl's case that is mostly package (class) names. Identifiers of important variables use capital letters so that they stand out from the rest; but in your ...

  2. Conditional statements, using if, else, elsif in Perl

    Passing multiple parameters to a function in Perl; Variable number of parameters in Perl subroutines; Returning multiple values or a list from a subroutine in Perl; ... Perl allows to add addition if-statements, both in the if-block and in the else-block. Note, the code inside the internal blocks is further indented to the right with another 4 ...

  3. Perl if Statement

    The limitation of the Perl if statement is that it allows you to execute a single statement only. If you want to execute multiple statements based on a condition, you use the following form: If you want to execute multiple statements based on a condition, you use the following form:

  4. creating a variable in an if statement

    Re: creating a variable in an if statement by Anonymous Monk on Jan 22, 2008 at 21:59 UTC: When you're writing code, keep it simple and clear. Nothing else really matters. If you want to confine a certain variable to a limited scope, it's fine to use "{}" braces to create a block, put "my" variable declarations inside that block and go-to-town.

  5. If statement in Perl

    The statements gets executed only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored. Example: In the following example, we have an integer value assigned to variable "num". Using if statement, we are checking whether the value assigned to num is less than 100 or not.

  6. Perl

    In Perl, we use variables to access data stored in a memory location(all data and functions are stored in memory). Variables are assigned with data values that are used in various operations. Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scalar data type that holds the location of another va

  7. Perl If-Else Statement

    An if-else statement is a conditional statement that executes one block of code if a specified condition is true, and another block of code if the condition is false. Syntax The syntax for the if-else statement in Perl is:

  8. Perl Else If Statement

    In this tutorial, we will learn about else-if statements in Perl. We will cover the basics of conditional execution using if-else-if statements. ... Declare a variable num. Assign a value to num. Use an if-else-if statement to check if num is positive, negative, or zero. Print a message indicating whether num is positive, ...

  9. Conditional Decisions

    Conditional Decisions. Perl conditional statements allow conditions to be evaluated or tested with a statement or statements to be executed per the condition value which can be either true or false. Perl does not have native boolean types. However, the numeric literal 0, the strings "0" and "", the empty array () and undef are all considered ...

  10. Perl If-Else Statement: A Comprehensive Guide

    This article will delve into the nitty-gritty of Perl's 'if-else' statement, providing examples, tips, and highlighting common errors to avoid. Understanding Perl's If-Else Statement; The 'if-else' statement is a conditional construct that checks a specific condition and performs an action based on whether the condition is true or false.

  11. Perl if, else, elsif ("else if") syntax

    Summary: This tutorial shows a collection of Perl if, else, and else if examples.. Here are some examples of the Perl if/else syntax, including the "else if" syntax, which is really elsif. (I wrote this because after working with many different languages I can never remember the "else if" syntax for most languages, and elsif is pretty rare.). The Perl if/else syntax

  12. Assignment to a value only if it is defined

    Replies are listed 'Best First'. Re: Assignment to a value only if it is defined by jettero (Monsignor) on Jan 20, 2010 at 12:01 UTC: If bar() is a complex function, then perhaps it should be the one returning the default value...

  13. Conditional Statements

    Conditional Statements. When ever you want to perform a set of operations based on a condition (s) If / If-Else / Nested ifs are used. You can also use if-else , nested IFs and IF-ELSE-IF ladder when multiple conditions are to be performed on a single variable. 1.

  14. if-else Statement

    Branches in Perl. We often need the execution of some portions of our code to be subject to a certain condition (s). Within the Perl programming language, the simplest and sometimes the most useful way of creating a condition within your program is through an if-else statement. Let's discuss if-else statements in detail, including nested-ifs ...

  15. Variable declaration in Perl

    Automatic string to number conversion or casting in Perl; Conditional statements, using if, else, elsif in Perl; Boolean values in Perl; Numerical operators; String operators: concatenation (.), repetition (x) ... We assign 42 to a variable. Later we increment it by one, and then print it. Surprisingly the variable still contains 42.

  16. The Essential Guide to Perl Variable

    To manipulate data in your program, you use variables. Perl provides three types of variables: scalars, lists, and hashes to help you manipulate the corresponding data types including scalars, lists, and hashes.. You'll focus on the scalar variable in this tutorial.

  17. The conditional (ternary) operator

    One way to reduce the verbosity of Perl code is to replace if-else statements with a conditional operator expression. The conditional operator (aka ternary operator) takes the form: logical test? value if true: value if false. Let's convert a standard Perl if-else into its conditional operator equivalent, using a fictitious subroutine.

  18. Use the logical-or and defined-or operators to provide default

    This is a more concise code pattern than using an if statement block. ... would include zero) and then use a ternary operator to either assign the value or return early. Defined-or. Since version 5.10.0 Perl has has had the defined-or operator ('//'). This will check if the variable is defined, and if it is not, Perl will execute the code ...

  19. perl

    You are right. And there is no difference. If you put the "if" in front you just have to put curly braces around the assignment. Perl allows for post- if statements and also allows for post- while, and post- for loops too. However, these things are usually discouraged because people scanning the code may miss the if.