while (<>) { print; }. will read either from a file specified on the command line or from stdin if no file is given. If you are required this loop ...
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
StackOverflowforTeamsismovingtoitsowndomain!Whenthemigrationiscomplete,youwillaccessyourTeamsatstackoverflowteams.com,andtheywillnolongerappearintheleftsidebaronstackoverflow.com.
Checkyouremailforupdates.
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
LearnmoreaboutCollectives
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
LearnmoreaboutTeams
ProgrammaticallyreadfromSTDINorinputfileinPerl
AskQuestion
Asked
12years,3monthsago
Modified
2monthsago
Viewed
160ktimes
80
New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore.
Whatistheslickestwaytoprogramaticallyreadfromstdinoraninputfile(ifprovided)inPerl?
perlstdin
Share
Improvethisquestion
Follow
askedJun29,2010at7:23
sykersyker
10.6k1616goldbadges5454silverbadges6868bronzebadges
Addacomment
|
8Answers
8
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
98
while(<>){
print;
}
willreadeitherfromafilespecifiedonthecommandlineorfromstdinifnofileisgiven
Ifyouarerequiredthisloopconstructionincommandline,thenyoumayuse-noption:
$perl-ne'print;'
Hereyoujustputcodebetween{}fromfirstexampleinto''insecond
Share
Improvethisanswer
Follow
editedJul8,2017at13:11
EugenKonkov
19.7k1212goldbadges9494silverbadges138138bronzebadges
answeredJun29,2010at7:28
ennuikillerennuikiller
45.6k1414goldbadges110110silverbadges137137bronzebadges
5
24
+1+nitpick:"willreadfromoneormorefilesconsecutivelyspecifiedonthecommandline"
– msw
Jun29,2010at7:57
5
...andallyouneedtodoiswrite@ARGV="/path/to/some/file.ext";anditreadsthefile--soyoucanevenprogramadefaultfileoncertainconditions.
– Axeman
Jun29,2010at13:54
3
Andifyourscriptisveryshort,youcanusethe-nor-poptionstoperl,andspecifyyourprocessingonthecommandline:perl-n-e'$_=uc($_);print;'yourfile.With-pinsteadof-n,perlautomaticallyprints$_attheend.
– mivk
Jan9,2012at10:46
3
Andofcourseyoucan"slurp"everythinginonego:my@slurp=<>;foreachmy$line(@slurp){...}
– DavidTonhofer
Dec19,2013at13:45
Isthereareasonyoudon'tnamethereadlinewithsomethinglikewhile(my$line=<>){...?
– DavidMertens
Jan20,2018at23:16
Addacomment
|
50
Thisprovidesanamedvariabletoworkwith:
foreachmy$line(){
chomp($line);
print"$line\n";
}
Toreadafile,pipeitinlikethis:
program.pl).Thennoredirectionisnecessary.
– DavidMertens
Jul7,2014at16:12
3
Thefirstlineshouldreadforeachmy$line(){[email protected]'snotPerl'sfaultifPerlscriptsareunreadable.Programmersaretoblamehere!
– tiktak
Dec13,2014at13:01
3
Rereadingthequestionthisresponseisincorrectbecauseitonlyreadsfromstdinanddoesn'treadafilespecifiedonthecommandline.ennuikiller'sansweriscorrectalthoughIwouldwriteitaswhile(my$line=<>){print$line;}.
– MikeKulls
Dec14,2014at23:35
3
@MikeKullsShouldn'tthatbewhile(my$line=<>,defined$line){...}orwhile(<>){my$line=$_;}toavoidstoppingonablankline?
– GregNisbet
Dec14,2016at21:14
|
Show2morecomments
17
The"slickest"wayincertainsituationsistotakeadvantageofthe-nswitch.Itimplicitlywrapsyourcodewithawhile(<>)loopandhandlestheinputflexibly.
InslickestWay.pl:
#!/usr/bin/perl-n
BEGIN:{
#dosomethingoncehere
}
#implementlogicforasinglelineofinput
print$result;
Atthecommandline:
chmod+xslickestWay.pl
Now,dependingonyourinputdooneofthefollowing:
Waitforuserinput
./slickestWay.pl
Readfromfile(s)namedinarguments(noredirectionrequired)
./slickestWay.plinput.txt
./slickestWay.plinput.txtmoreInput.txt
Useapipe
someOtherScript|./slickestWay.pl
TheBEGINblockisnecessaryifyouneedtoinitializesomekindofobject-orientedinterface,suchasText::CSVorsomesuch,whichyoucanaddtotheshebangwith-M.
-land-parealsoyourfriends.
Share
Improvethisanswer
Follow
answeredFeb10,2014at17:25
NeilBestNeilBest
79988silverbadges1616bronzebadges
Addacomment
|
15
Youneedtouse<>operator:
while(<>){
print$_;#orsimply"print;"
}
Whichcanbecompactedto:
printwhile(<>);
Arbitraryfile:
openmy$F,"){
print$_;
}
close$F;
Share
Improvethisanswer
Follow
editedAug22at13:41
MUYBelgium
2,20244goldbadges3030silverbadges4343bronzebadges
answeredJun29,2010at7:25
el.pescado-нетвойнеel.pescado-нетвойне
18.5k44goldbadges4545silverbadges8686bronzebadges
Addacomment
|
10
Ifthereisareasonyoucan'tusethesimplesolutionprovidedbyennuikillerabove,thenyouwillhavetouseTypeglobstomanipulatefilehandles.Thisiswaymorework.Thisexamplecopiesfromthefilein$ARGV[0]tothatin$ARGV[1].ItdefaultstoSTDINandSTDOUTrespectivelyiffilesarenotspecified.
useEnglish;
my$in;
my$out;
if($#ARGV>=0){
unless(open($in,"=1){
unless(open($out,">",$ARGV[1])){
die"couldnotopen$ARGV[1]forwriting.";
}
}
else{
$out=*STDOUT;
}
while($_=){
$out->print($_);
}
Share
Improvethisanswer
Follow
answeredDec7,2014at18:52
Sigusr2Sigusr2
10911silverbadge22bronzebadges
2
1
+1forawaythatwillworkiffilenametoreadfromisnotprovidedoncommandlinebutsomewhereelse(insomevariable,readfromconfigfileetc-youjustreplace$ARGV[0]etcwithothervariable)whereallotheranswersfail...
– MatijaNalis
Oct30,2016at16:29
Or,forreading,justunshiftthefilenameonto@ARGVandusethediamondoperator,<>.
– DavidMertens
Jan20,2018at23:04
Addacomment
|
6
Do
$userinput=;#readstdinandputitin$userinput
chomp($userinput);#cutthereturn/linefeedcharacter
ifyouwanttoreadjustoneline
Share
Improvethisanswer
Follow
answeredJan24,2013at13:59
ThorstenNiehuesThorstenNiehues
13.2k2020goldbadges7575silverbadges108108bronzebadges
1
OnlyreadsfromSTDIN,notfromspecifiedfile.ThediamondoperatorisexactlywhattheOPislookingfor.
– DavidMertens
Jan20,2018at23:14
Addacomment
|
-1
HereishowImadeascriptthatcouldtakeeithercommandlineinputsorhaveatextfileredirected.
if($#ARGV<1){
@ARGV=();
@ARGV=<>;
chomp(@ARGV);
}
Thiswillreassignthecontentsofthefileto@ARGV,fromthereyoujustprocess@ARGVasifsomeonewasincludingcommandlineoptions.
WARNING
Ifnofileisredirected,theprogramwillsittheiridlebecauseitiswaitingforinputfromSTDIN.
IhavenotfiguredoutawaytodetectifafileisbeingredirectedinyettoeliminatetheSTDINissue.
Share
Improvethisanswer
Follow
answeredSep20,2015at18:01
WestrockWestrock
16944silverbadges1414bronzebadges
1
Thisisacoolapproach,butnotwhattheOPwasaskingfor.Thismakesitpossibletopassasinglefilenameasanargument,thecontentsofwhichareusedascommand-linearguments.OPwaslookingforsomethingdifferent.Also,whythecryptic$#ARGV<1insteadof(whatIthinkofas)moreclear@ARGV==1?
– DavidMertens
Jan20,2018at23:12
Addacomment
|
-3
if(my$file=shift){#iffileisspecified,readfromthat
open(my$fh,'){
print$line;
}
}
else{#otherwise,readfromSTDIN
printwhile(<>);
}
Share
Improvethisanswer
Follow
answeredJun29,2010at7:44
trapd00rtrapd00r
722bronzebadges
2
8
Theplain<>operatorwillautomaticallyfindandreadfromanyfile(s)givenonthecommandline.There'snoneedfortheif.
– DaveSherohman
Jun29,2010at8:27
Youalsodonotdescribewhatshiftisdoinghere
– EugenKonkov
Jul8,2017at13:14
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedperlstdinoraskyourownquestion.
TheOverflowBlog
IntroducingtheOverflowOfflineproject
Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499)
FeaturedonMeta
The2022Community-a-thonhasbegun!
Mobileappinfrastructurebeingdecommissioned
CollectivesUpdate:RecognizedMembers,Articles,andGitLab
The[script]tagisbeingburninated
StagingGroundWorkflow:CannedComments
Linked
11
Howtogetremotebranchnameingitpre-pushhook
0
ignoremalformedXMLwithPerl-XML
0
PerlmoduleFile:SlurpwithSTDINpiped
Related
1698
HowdoIreadfromstdin?
76
ReadfromFile,orSTDIN
749
HowtofixalocalesettingwarningfromPerl
585
WhydoesmodernPerlavoidUTF-8bydefault?
308
HowtoreadfromafileorstandardinputinBash
14
CanIpromptforuserinputafterreadingpipedinputonSTDINinPerl?
2
HowtoreadSTDINandwritecontentbacktoSTDINinPerl?
248
HowtoreadfromstdinlinebylineinNode
67
Readalltextfromstdintoastring
HotNetworkQuestions
Minimumrotationtogetthemaximumvalue
Whatisthemostefficientwaytoget110Vfrom220Vsingle-phasewiring?
WorkplaceSafetyPolicyMakesMeLessSafe
QGISdelimitedtextlayerisnotvisible
Pianochordswithanoctaveinthem
HowcanApophishaveason?
HowdoIlabelatablelikethis?
HowcanIprintoutthefirstlineofallthefilesthatmatchcertain"find"criteria?
Whyarefangsofgirlssocommoninanime?
Basaltsill-acontradictioninterms?
Ifform8606isnotrequiredtosubmitforjustRothIRAcontributions?HowdoesIRSenforcethelimit?
Istriplebranchingnecessaryinmakingasyntaxtreefor'thegirlintheroomwavedtome'?
Plotasequenceoffunctionsinoneplot
Havefundamentalparticlesbeenobserved?
Mylibrarymembershipnumber
Whydocourtopinionslistmultiplelayersofcitations?
HowdoyoudescribesomeoneasashapeshifterinLatin?
Isthereawayasocietycouldproducetanksascheaplyascars?
Bootablefloppydisk
WhyareringsnotafavoriteoptioninITnetworks?
HowcanIconnectTikZnodeswithmultiple-cornerlines?
Whydoweneedmixedstatesinquantummechanics?
Firstoccurrenceofacharacterbeingphilosophicallyoverwhelmedbythemultiverse
Wouldlanguagehavemeaningiftherewasnoconsciousness?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-perl
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings