#!/usr/bin/perl -w use strict; # usage: AskAtom.pl SomeFile # First line of "SomeFile" is the output file name. # Program asks the user for a value which is # appended to each line of the subsequent lines # in "SomeFile". my ($fileIN) = @ARGV; #first command line arg is $fileIN open(my $in, "<", $fileIN) or die "Can't open $fileIN: $!"; #The $newFile name is on the first line of "somefile" my $newFile = <$in>; #read the first line of $fileIN $newFile =~ s/^\s*//; #delete leading spaces (optional) $newFile =~ s/\s*$//; #delete trailing spaces (also does chomp()) my $atom = ask_user4atom(); open (my $out, ">", $newFile) or die "Can't write to $newFile :$!"; while (<$in>) #reading of <$in> starts again at 2nd line { chomp; #deletes line endings next if /^\s*$/; #skip blank lines (a blank line at the end # of the file is not an error) print $out "$_-$atom\n"; #append $atom to each line } #When asking user a question - blank line is just a #re-prompt. Spaces before or after the user input #also do not matter...That is standard CMD Line... sub ask_user4atom { my $atom; while ( (print "Enter atom symbol: "), $atom =<STDIN>) { next if $atom =~ /^\s*$/; #re-prompt on a blank line $atom =~ s/^\s*//; #delete leading spaces $atom =~ s/\s*$//; #delete trailing spaces return $atom; } } #Note: In a short running script like this, there is # no need to explictly close() files. The O/S will do that # when the script finishes - no biggie. # A File Handle is an O/S resource, but here this is not # significant. =Example file: ChemIn.txt Chemout.txt ABC XYZ =End ChemIn.txt =Example Command Line Output C:\TEMP>perl askatom.pl ChemIn.txt Enter atom symbol: Enter atom symbol: Na C:\TEMP>type ChemIn.txt ChemOut.txt ABC XYZ C:\TEMP>type ChemOut.txt ABC-Na XYZ-Na =END of Example Command Line Output
In reply to Re: fileHandle vs prompt
by Marshall
in thread fileHandle vs prompt
by jfjobidon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |