On Tue, 18 Mar 2003, Scott R. Godin wrote:

> John W. Krahn wrote:
> 
> > David Gilden wrote:
> >> 
> >> OK, one problem is solved, which was the path to the data file.
> >> I know there is a simple way to read in a file like the following:
> >> 
> >> apple,2
> >> banana,4
> >> kiwi,1
> >> 
> >> and produce a HASH. The code below works I get the feeling there is a
> >> more compact way to accomplish this.
> > 
> > Yes, there is.  :-)
> > 
> > my %hash = do { local $/; <FH> =~ /[^\n,]+/g };
> 
> Holy Handgrenades, Batman!
> 
> but where's the implicit split of key and value there? forgive me for 
> asking, but I just don't see it. is there some magic going on here? 

Step 1) local $/

$/ (input record separator) defines what constitutes a line in perl. By 
default it is set "\n". The statement "local $/" undefines $/ within 
this do block i.e. you are now operating in slurp mode.

perldoc perlvar # Search for INPUT_RECORD_SEPARATOR


Step 2) <FH> =~ /[^\n,]+/g

Remember you are in slurp mode, so a <FH> would return the string
"apple,2\nbanana,4\nkiwi,1\n". The regex matches anything that is not a 
',' or "\n" and thus performing the split for you.

The do block returns the value of the last statement, in this case the 
result of the regex in a list context due to the my %hash = do {...}

The returned list is ('apple', 2, ....) which gets assigned to %hash and everybody is 
happy :-)

hth


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to