Perl | exists() Function - GeeksforGeeks (2024)

Skip to content

Perl | exists() Function - GeeksforGeeks (1)

Last Updated : 07 May, 2019

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.

Syntax: exists(Expression)

Parameters:
Expression : This expression is either array or hash on which exists function is to be called.

Returns: 1 if the desired element is present in the given array or hash else returns 0.

Example 1: This example uses exists() function over an array.

#!/usr/bin/perl

# Initialising an array

@Array = (10, 20, 30, 40, 50);

# Calling the for() loop over

# each element of the Array

# using index of the elements

for ($i = 0; $i < 10; $i++)

{

# Calling the exists() function

# using index of the array elements

# as the parameter

if(exists($Array[$i]))

{

print "Exists\n";

}

else

{

print "Not Exists\n"

}

}


Output:

ExistsExistsExistsExistsExistsNot ExistsNot ExistsNot ExistsNot ExistsNot Exists

In the above code, it can be seen that parameter of the exists() function is the index of each element of the given array and hence till index 4 (index starts from 0) it gives output as “Exists” and later gives “Not Exists” because index gets out of the array.

Example 2: This example uses exists() function over a hash.

#!/usr/bin/perl

# Initialising a Hash

%Hash = (Mumbai => 1, Kolkata => 2, Delhi => 3);

# Calling the exists() function

if(exists($Hash{Mumbai}))

{

print "Exists\n";

}

else

{

print "Not Exists\n"

}

# Calling the exists() function

# with different parameter

if(exists($Hash{patna}))

{

print "Exists\n";

}

else

{

print "Not Exists\n"

}

Output :

ExistsNot Exists

In the above code, exists() function takes the key of the given hash as the parameter and check whether it is present or not.



Please Login to comment...

Similar Reads

Perl | Basic Syntax of a Perl Program

Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar

10 min read

Perl | chomp() Function

The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &amp;quo

2 min read

Perl | chop() Function

The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string $string = &quot;GfG is a computer science portal&quot;; # Calling the chop

1 min read

Perl | rename() Function

rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters: old_file_path: path of the old file along with its name new_file_path: path of the new file along with its name Returns 0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename()

1 min read

Perl | cos() Function

This function is used to calculate cosine of a VALUE or $_ if VALUE is omitted. The VALUE should be expressed in radians. Syntax: cos(VALUE) Parameters: VALUE in the form of radians Returns: Function returns cosine of VALUE. Example 1: #!/usr/bin/perl # Calling cos function $var = cos(5); # Printing value of cos(5) print &quot;cos value of 5 is $va

1 min read

Perl | sin() Function

This function is used to calculate sine of a VALUE or $_ if VALUE is omitted. This function always returns a floating point. Syntax: sin(VALUE) Parameters: VALUE in the form of float Returns: Function returns sine of VALUE. Example 1: #!/usr/bin/perl # Calling sin() function $var = sin(5); # Printing value for sin(5) print &quot;sin value of 5 is $

1 min read

Perl | abs() function

This function returns the absolute value of its argument. If a pure integer value is passed then it will return it as it is, but if a string is passed then it will return zero. If VALUE is omitted then it uses $_ Syntax: abs(VALUE) Parameter: VALUE: It is a required number which can be either positive or negative or a string. Returns: Function retu

2 min read

Perl | atan2() Function

This function is used to calculate arctangent of Y/X in the range -PI to PI. Syntax: atan2(Y, X) Parameters: Y and X which are axis values Returns: Function returns arctangent of Y/X in the range -PI to PI. Example1: #!/usr/bin/perl # Assigning values to X and y $Y = 45; $X = 70; # Calling atan2() function $return_val = atan2($Y, $X); # printing th

1 min read

Perl | splice() - The Versatile Function

In Perl, the splice() function is used to remove and return a certain number of elements from an array. A list of elements can be inserted in place of the removed elements. Syntax: splice(@array, offset, length, replacement_list) Parameters: @array - The array in consideration. offset - Offset of removal of elements. length - Number of elements to

9 min read

Perl | delete() Function

Delete() in Perl is used to delete the specified keys and their associated values from a hash, or the specified elements in the case of an array. This operation works only on individual elements or slices. Syntax: delete(LIST) Parameters: LIST which is to be deleted Returns: undef if the key does not exist otherwise it returns the value associated

1 min read

Perl | defined() Function

Defined() in Perl returns true if the provided variable 'VAR' has a value other than the undef value, or it checks the value of $_ if VAR is not specified. This can be used with many functions to detect for the failure of operation since they return undef if there was a problem. If VAR is a function or reference of a function, then it returns true

2 min read

Perl | each() Function

This function returns a Two-element list consisting of the key and value pair for the next element of a hash when called in List context, so that you can iterate over it. Whereas it returns only the key for the next element of the hash when called in scalar context. Syntax: each MY_HASH Parameter: MY_HASH is passed as a parameter to this function R

1 min read

Perl | index() Function

This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position. By default, it searches from the beginning(i.e. from index zero). Syntax: # Searches pat in text from given index index(text, pat, index) # Searches pat in text index(text, pat) Parameters: text: String in

3 min read

Perl | int() function

int() function in Perl returns the integer part of given value. It returns $_ if no value provided. Note that $_ is default input which is 0 in this case. The int() function does not do rounding. For rounding up a value to an integer, sprintf is used. Syntax: int(VAR) Parameters: VAR: value which is to be converted into integer Returns: Returns the

1 min read

Perl | join() Function

join() function in Perl combines the elements of LIST into a single string using the value of VAR to separate each element. It is effectively the opposite of split. Note that VAR is only placed between pairs of elements in the LIST; it will not be placed either before the first element or after the last element of the string. Supply an empty string

1 min read

Perl | keys() Function

keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function. Syntax: keys(HASH) Parameter: HASH: Hash whose keys are to be printed Return: For scalar context, it returns the number of keys in the hash whereas for List

1 min read

Perl | lc() Function for Lower Case Conversion

lc() function in Perl returns a lowercased version of VAR, or $_ if VAR is omitted. Syntax: lc(VAR)Parameter: VAR: Sentence which is to be converted to lower caseReturn: Lowercased version of VAR, or $_ if VAR is omitted Example 1: C/C++ Code #!/usr/bin/perl # Original String containing both # lower and upper case letters $original_string = &quot;G

1 min read

Perl | lcfirst() Function

lcfirst() function in Perl returns the string VAR or $_ after converting the First character to lowercase. Syntax: lcfirst(VAR) Parameter: VAR: Sentence whose first character is to be converted to lower case Returns: the string VAR or $_ with the first character lowercased Example 1: #!/usr/bin/perl # Original String containing both # lower and upp

1 min read

Perl | length() Function

length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Syntax:length(VAR) Parameter: VAR: String or a group of strings whose length is to be calculated Return: Returns the size of the string. Example 1: #!/usr/bin/perl # String whose length is to be calculated $orignal_string = &quot;Geeks for Geeks

1 min read

Perl | substr() function

substr() in Perl returns a substring out of the string passed to the function starting from a given index up to the length specified. This function by default returns the remaining part of the string starting from the given index if the length is not specified. A replacement string can also be passed to the substr() function if you want to replace

2 min read

Perl | oct() Function

oct() function in Perl converts the octal value passed to its respective decimal value. For example, oct('1015') will return '525'. This function returns the resultant decimal value in the form of a string which can be used as a number because Perl automatically converts a string to a number in numeric contexts. If the passed parameter is not an oc

1 min read

Perl | log() Function

log() function in Perl returns the natural logarithm of value passed to it. Returns $_ if called without passing a value. log() function can be used to find the log of any base by using the formula: Syntax: log(value) Parameter: value: Number of which log is to be calculated Returns: Floating point number in scalar context Example 1: #!/usr/bin/per

2 min read

Perl | push() Function

push() function in Perl is used to push a list of values onto the end of the array. push() function is often used with pop to implement stacks. push() function doesn't depend on the type of values passed as list. These values can be alpha-numeric. Syntax: push(Array, List) Parameter: Array: in which list of values is to be added List: which is to b

1 min read

Perl | rand() Function

rand() function in Perl returns a random fractional number between 0 and the positive number value passed to it, or 1 if no value is specified. Automatically calls srand() to seed the random number generator unless it has already been called. Syntax: rand(range_value) Parameter: range_value: a positive number to specify the range Returns: a random

1 min read

Perl | prototype() Function

prototype() function in Perl returns a string containing the prototype of the function or reference passed to it as an argument, or undef if the function has no prototype. Syntax: prototype(function_name) Parameter: function_name: Function whose prototype is to be determined Returns: prototype of the function passed or undef if no prototype exists

1 min read

Perl | reset() Function

reset() function in Perl resets (clears) all package variables starting with the letter range specified by value passed to it. Generally it is used only within a continue block or at the end of a loop. Note: Use of reset() function is limited to variables which are not defined using my() function. Syntax: reset(letter_range) Parameter: letter_range

2 min read

Perl | quotemeta() Function

quotemeta() function in Perl escapes all meta-characters in the value passed to it as parameter. Example: Input : "GF*..G" Output : "GF\*\.\.G" Syntax: quotemeta(value) Parameter: value: String containing meta-characters Return: a string with all meta-characters escaped Example 1: #!/usr/bin/perl -w $string = &quot;GF*\n[.]*G&quot;; print &quot;Ori

1 min read

Perl | Array pop() Function

pop() function in Perl returns the last element of Array passed to it as an argument, removing that value from the array. Note that the value passed to it must explicitly be an array, not a list. Syntax: pop(Array) Returns: undef if list is empty else last element from the array. Example 1: #!/usr/bin/perl -w # Defining an array of integers @array

1 min read

Perl | return() Function

return() function in Perl returns Value at the end of a subroutine, block, or do function. Returned value might be scalar, array, or a hash according to the selected context. Syntax: return Value Returns: a List in Scalar Context Note: If no value is passed to the return function then it returns an empty list in the list context, undef in the scala

2 min read

Perl | reverse() Function

reverse() function in Perl when used in a list context, changes the order of the elements in the List and returns the List in reverse order. While in a scalar context, returns a concatenated string of the values of the List, with each character of the string in the opposite order. Syntax: reverse List Returns: String in Scalar Context and List in L

1 min read

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

Perl | exists() Function - GeeksforGeeks (4)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

Perl | exists() Function - GeeksforGeeks (2024)
Top Articles
About Banks Power
Top 5 Impacts of AI in Banking
Antisis City/Antisis City Gym
Matgyn
Minooka Channahon Patch
Fat Hog Prices Today
Www.craigslist Augusta Ga
South Carolina defeats Caitlin Clark and Iowa to win national championship and complete perfect season
Words From Cactusi
Snarky Tea Net Worth 2022
Uvalde Topic
Epaper Pudari
R/Altfeet
Amelia Bissoon Wedding
Robert Malone é o inventor da vacina mRNA e está certo sobre vacinação de crianças #boato
Where does insurance expense go in accounting?
Walthampatch
People Portal Loma Linda
TS-Optics ToupTek Color Astro Camera 2600CP Sony IMX571 Sensor D=28.3 mm-TS2600CP
Spartanburg County Detention Facility - Annex I
Playgirl Magazine Cover Template Free
Mals Crazy Crab
The Blind Showtimes Near Amc Merchants Crossing 16
Breckie Hill Mega Link
Little Rock Skipthegames
Craigslist Pennsylvania Poconos
Craigslist Dubuque Iowa Pets
Hdmovie2 Sbs
1979 Ford F350 For Sale Craigslist
Carroway Funeral Home Obituaries Lufkin
Abga Gestation Calculator
Town South Swim Club
Elanco Rebates.com 2022
M3Gan Showtimes Near Cinemark North Hills And Xd
Goodwill Thrift Store & Donation Center Marietta Photos
Watchseries To New Domain
Whitehall Preparatory And Fitness Academy Calendar
Dynavax Technologies Corp (DVAX)
Tirage Rapid Georgia
Sabrina Scharf Net Worth
Let's co-sleep on it: How I became the mom I swore I'd never be
Atom Tickets – Buy Movie Tickets, Invite Friends, Skip Lines
Www.craigslist.com Waco
Subdomain Finder
Comanche Or Crow Crossword Clue
Babykeilani
Beds From Rent-A-Center
Wild Fork Foods Login
Deviantart Rwby
The Significance Of The Haitian Revolution Was That It Weegy
Ark Silica Pearls Gfi
Duffield Regional Jail Mugshots 2023
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 5820

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.