Special variables in Perl - GeeksforGeeks
文章推薦指數: 80 %
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$_=
延伸文章資訊
- 1Special Variables - PERL - kichwa.com
$], The first part of the string printed out when you say perl -v. It can be used to determine at...
- 2Perl predefined variables - Perldoc Browser
CONTENTS. General Variables; Variables related to regular expressions; Variables related to fileh...
- 3Special Variables - Perl 101
Perl has rich signal handling capabilities; using the %SIG variable, you can make any subroutine ...
- 4Perl Special Variables - CodesCracker
Special variables are predefined having special meaning in perl. The special variables in perl, u...
- 5perlvar - Perl predefined variables - Perldoc Browser
SPECIAL VARIABLES. The following names have special meaning to Perl. Most punctuation names have ...