Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: problems with split

by integral (Hermit)
on Mar 03, 2003 at 18:20 UTC ( #240104=note: print w/replies, xml ) Need Help??

in reply to problems with split

The problem with your code is that the print statement is outside of the foreach loop (its outside of the curly braces which define the extent of the loop). To get it to print the second field on each line, this statement should be inside the loop so that it gets called for each line.
# type value value2 # 503 1093 4395 # load the data @file = <FILE>; # or use a while (defined(my $line = <FILE>)) { loop for my $line (@file) { # for is the same as foreach my @fields = split (/\s+/, $line); # @file was being reused print "$fields[2]\n"; }

integral, resident of freenode's #perl

Replies are listed 'Best First'.
Re: Re: problems with split
by Anonymous Monk on Mar 03, 2003 at 18:23 UTC
    can I do this without the filehandles?? cheers ;->
      You have to use a filehandle to read data in from a file, but for a simple program you can get away with using a <> to load data from the files listed in @ARGV (or STDIN if no files are given) with perl automatically opening them as needed.
      while (<>) { print (split /\s+/)[2], "\n"; }

      integral, resident of freenode's #perl

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://240104]
[shmem]: hmm.. which makes emerge the question: is there a way to attach a subroutine to a variable, which is run as soon as that variable changes?
[moritz]: through a tie?
[shmem]: moritz: of course!
shmem slaps forehead m(
[shmem]: consider, then, @CBMonks as a tied variable which triggers withdrawing empty cups and serving new ones
[GotToBTru]: it's always teatime somewhere

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2017-04-24 12:23 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (439 votes). Check out past polls.