Easy or even Possible? file I/O + user input

2003-08-24 Thread Tor Hildrum
A challenge was posted on a forum I frequent, and
when trying to golf down my solution I came across
something of a conundrom.
The challenge is simple:
Take a filename and a word on the commandline
or stdin and print the number of occurences the word
has in the file.
Now, I don't want to use open() or @ARGV, because
that's bad form(?), ie long.
Well, my final solution, that isn't really a solution was:
-0ne '@a=/WORD/g;print [EMAIL PROTECTED]'
Now, this isn't really a solution because it has the WORD
hardcoded. But, how would I be able to get the WORD
when using -n? I'm guessing this isn't possible.
So, how would one get the 2 values from the command-line
or stdin without spending so much code on open() and ARGV?
Tor



Re: Easy or even Possible? file I/O + user input

2003-08-24 Thread Eugene van der Pijll
En op 24 augustus 2003 sprak Tor Hildrum:
> Well, my final solution, that isn't really a solution was:
> -0ne '@a=/WORD/g;print [EMAIL PROTECTED]'
> 
> Now, this isn't really a solution because it has the WORD
> hardcoded. But, how would I be able to get the WORD
> when using -n? I'm guessing this isn't possible.

If the word is the second parameter on the command line, that is easy.
In the first pass of the -n loop, the first value of @ARGV is shifted
off, but the rest of @ARGV is left intact until the eond of the first
file is reached. So if the word is last on the command line, you can
just use pop inside the -n loop:

perl -0ne'print s/${\pop}//g' file word

If the word is the first argument, then you have a problem. You have to
remove the word from @ARGV _before_ the first pass of the -n loop, which
means you have to use an INIT block (often too long!):

perl -0ne'INIT{$a=shift}print s/$a//g' word file

By the way, it's better to use -p here. -p is often shorter than print,
especially if you're already using -n.

perl -0pe'$_=s/${\pop}//g' file word

Eugene

-- 
Pluralitas non est ponenda sine neccesitate -- \\/illiam of ()ckham