Special variables in Perl - GeeksforGeeks

文章推薦指數: 80 %
投票人數:10人

Special Variables in Perl are those which are already defined to carry out a specific function when required. Skiptocontent CoursesForWorkingProfessionalsDSAClasses(Live)SystemDesign(Live)JavaBackendDeveloper(Live)FullStack(Live)ExploreMoreLiveCoursesDSA(Self-Paced)SDETheory(Self-Paced)AllDevelopmentCourses(Self-Paced)ExploreMoreSelf-PacedCoursesForStudentsCompetitiveProgramming(Live)GATECourse2023(Live)DataScience(Live)ExploreMoreLiveCoursesDSA(Self-Paced)CIP(Self-Paced)JAVA/Python/C++(Self-Paced)ExploreMoreSelf-PacedCoursesSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#SQLScalaPerlGoLanguageKotlinWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesBusinessStudies(Class11th)BusinessStudies(Class12th)CSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersUPSCGeographyNotesHistoryNotesScience&Tech.NotesEthicsNotesPolityNotesEconomicsNotesUPSCPreviousYearPapersSSCCGLSSCCGLSyllabusGeneralStudiesEnglishReasoningSubjectwisePracticePapersPreviousYearPapersBankingExamsSBIClerkSBIClerkSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilitySBIClerkPracticePapersSBIPOSBIPOSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilityPreviousYearPapersSBIPOPracticePapersIBPSPOIBPSPO2022SyllabusEnglishNotesReasoningNotesPreviousYearPapersMockQuestionPapersIBPSClerkIBPSClerkSyllabusEnglishNotesPreviousYearPapersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWrite&EarnJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPerl|split()FunctionPerl|push()FunctionPerl|chomp()FunctionPerl|exists()FunctionPerl|substr()functionPerl|grep()FunctionPerl|PolymorphisminOOPsPerl|RegularExpressionsPerl|Arrays(push,pop,shift,unshift)Perl|StringOperatorsPerl|length()FunctionPerl|ArraysPerl|Loops(for,foreach,while,do...while,until,Nestedloops)Perl|AutomaticStringtoNumberConversionorCastingPerl|sleep()FunctionPerl|Removingleadingandtrailingwhitespaces(trim)Perl|SubroutinesorFunctionsPerl|substitutionOperatorPerl|eqoperatorPerl|RegexCheatSheetPerl|BooleanValuesPerl|SearchinginaFileusingregexUseofprint()andsay()inPerlPerl|join()FunctionPerl|MultidimensionalArraysIntroductiontoPerlRoleofSemiColoninvariousProgrammingLanguagesPerl|ArraySlicesHelloWorldPrograminPerlPerl|mykeywordPerl|split()FunctionPerl|push()FunctionPerl|chomp()FunctionPerl|exists()FunctionPerl|substr()functionPerl|grep()FunctionPerl|PolymorphisminOOPsPerl|RegularExpressionsPerl|Arrays(push,pop,shift,unshift)Perl|StringOperatorsPerl|length()FunctionPerl|ArraysPerl|Loops(for,foreach,while,do...while,until,Nestedloops)Perl|AutomaticStringtoNumberConversionorCastingPerl|sleep()FunctionPerl|Removingleadingandtrailingwhitespaces(trim)Perl|SubroutinesorFunctionsPerl|substitutionOperatorPerl|eqoperatorPerl|RegexCheatSheetPerl|BooleanValuesPerl|SearchinginaFileusingregexUseofprint()andsay()inPerlPerl|join()FunctionPerl|MultidimensionalArraysIntroductiontoPerlRoleofSemiColoninvariousProgrammingLanguagesPerl|ArraySlicesHelloWorldPrograminPerlPerl|mykeywordSpecialvariablesinPerlViewDiscussion ImproveArticle SaveArticle LikeArticle LastUpdated: 21Nov,2019ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle SpecialVariablesinPerlarethosewhicharealreadydefinedtocarryoutaspecificfunctionwhenrequired.ThedifferentiatingfactorbetweenaspecialVariableinPerlandarandomcharacteristheuseofPunctuationmarkafterthevariable,thesecouldbe@,$or%,etc,forexample,$_.PerlVariableshelpsadeveloperinsavingtimesincethesearegenerallyshortcutstobiggercommandsinEnglish.Note:Themostcommonspecialvariableis$_,whichisusedtostorethedefaultinput.Lookatthefollowingcodestogetanideaaboutthisspecialvariable:#Providingsomeinput while(<>) {     #Printingthedefaultvalue     #storedin$_    printlc($_); }Thisisthesameas#!/usr/bin/perlwhile($abc=<>) {    printlc($abc);}Followingisanexampleoftheabovementionedspecialvariableinworkingformat:#!/usr/bin/perlforeach('Mango','Orange','Apple'){   print($_);   print("\n");}Output:Theoutputoftheabovecodewillbe: Mango Orange Apple TypesofSpecialVariablesSpecialVariablescanbecategorizedonthebasisoftheirusageandnature.Theseare:RegularExpressionSpecialVariablesFilehandleSpecialVariablesGlobalScalarSpecialVariablesGlobalArraySpecialVariablesGlobalHashSpecialVariablesGlobalSpecialConstantsGlobalSpecialFilehandlesRegularExpressionSpecialVariables$digit:Themainfunctionof$digitistoholdthetextmatchedinasimilarsetofparenthesesinthelastmatchedpattern.However,patternsalreadymatchedinanestedblockarenotcounted.$&,$MATCH:Usedtofindthestringmatchedinthelastsuccessfulpatternsearch.ThoughMatchedinahiddenblockorenclosedinthecurrentsetarenotcounted.Thisisaread-onlyvariableandisscopeddynamically.#!/usr/bin/perl  #Declaringlocalstringlocal$_='abcdefghi';  #Patternmatching/def/;  #Printingthematchedpatternprint"$&\n";  Output: def $`,$PREMATCH:Thestringprecedingaquotedstringwasmatchedwiththelastsuccessfulpatternmatch.Itdoesn’tcountanymatchesenclosedwithinablockorevalenclosedbythecurrentblock.#!/usr/bin/perl  #Declaringlocalstringlocal$_='abcdefghi';  #Patternmatching/def/;  #Prematchingthepatternprint"$`:$&\n";  Output: abc:def $’,$POSTMATCH:Thestringfollowingwhateverwasmatchedbythelastsuccessfulpatternmatchnotcountinganymatcheshiddenwithinablockorevalenclosedbythecurrentblock.#!/usr/bin/perl  #Declaringlocalstringlocal$_='abcdefghi';  #Patternmatching/def/;  #Postmatchingthepatternprint"$&:$'\n";  Output: def:ghi FilehandleSpecialVariables$|,$OUTPUT_AUTOFLUSH:Ifsettononzero,thisvariableforcesaflushaftereverywriteorprintstatementontheoutputchannelthatiscurrentlybeingselected.$%,$FORMAT_PAGE_NUMBER:Thisvariablefindsthecurrentlyselectedoutputchannelandthecurrentpagenumber.$=,$FORMAT_LINES_PER_PAGE:Thisvariablereturnsthecurrentpagelengthi.e.thelineswhichareprintableofthecurrentlyselectedoutputchannel.Thedefaultvalueforthisvariableis60.$-,$FORMAT_LINES_LEFT:Returnsthenumberoflinesleftonthepageofthecurrentlyselectedoutputchannel.$~,$FORMAT_NAME:Thenameofthecurrentreportformatforthecurrentlyselectedoutputchannel.Thedefaultvalueisthenameofthefilehandle.Forexample,forSTDOUT,thedefaultformatnamewouldbeSTDOUTitself.GlobalScalarSpecialVariablesBelowmentionedisthelistofsomeofthescalarspecialvariables.AndlistedcorrespondingEnglishlikenamesalongwiththesymbolicnames.$_,$ARG:Usedasadefaultvariabletoacceptinputandtoperformpattern-searching,whenvariableisomitted.$.,$NR:Containsthelinenumberofthefilehandlelastupdated.Thevalueisresettozeroifthefilehandleisclosed.Thisvariablewillnevermovetheseekpointerinthefile.$/,$RS:Thisistheinputrecordseparator.If$/isundefined,theentirefileisreadasasingleinputfornullvalueablankisconsideredasadelimiter.Itcreatesanewlinebydefault.#!/usr/bin/perl  local$/;          #enable"slurp"modelocal$_=;   #wholefilenowheres/\n[\t]+//g;‘$,‘,$OFS:TheOutputFieldSeparatorcommandisusedwhentheuserwantstoprintadefaultvaluebetweeneachprintoperatorargument.Thedefaultvalueforthisvariableisundef.$\,$ORS:TheOutputRecordSeparatorcommandisusedwhentheuserwantstoprintthevalueatthelastoftheprintoperatorarguments.$!,$OS_ERRORor$ERRNO:Yieldsthecurrentvalueoferrorno.variableifusedinanumericcontext.Ifutilizedinastringcontext,ityieldsthecorrespondingsystemerrorstring.if(openmy$fh,"



請為這篇文章評分?