in reply to Re: Help with split() function
in thread Help with split() function

I've edited it down to this

#!usr/bin/env perl use warnings; use strict; open my $test_fh, '<', @ARGV or die "Can not open file $!\n"; while (<$test_fh>) { my @line = split (); # if ($line[1] =~ /P/i); print "$line[1]"; } close ($test_fh);

I'm still getting the same thing. I think my split() needs something but I have no idea what. Any help?

Replies are listed 'Best First'.
Re^3: Help with split() function
by cdarke (Prior) on Mar 19, 2008 at 02:02 UTC
    You have several problems here. The main one is that you decided to use split for no obvious reason. Yes it can be done that way, but why would you want to?

    The simplest would be just to use a regular expression to find a 'p' in the line, all you need is: print if /p/i; No split is required.

    Where split could be used is split '' which breaks up each character into a seperate list element. You could then test each one in a loop. This method is occasionally useful, but only for specialised character-by-character operations, not for a simple task like this. You also seem unclear as to what accessing an array is doing. I suggest you read the section on arrays before you try to use them.

    Keep plugging with the book, and keep writing Perl.
Re^3: Help with split() function
by halfcountplus (Hermit) on Mar 19, 2008 at 02:16 UTC
    Well, here's what i would do, and presuming i can still read the output is tested and correct:

    #!/usr/bin/perl -w use strict; while (<DATA>) { my @line = split (); foreach my $word (@line) { if ($word =~ /P/i) { print "$word\n"; } } } __DATA__ CPAN stands for comprehensive Perl Archive Network. ^ and $ are used as anchors in a regular expression. /pattern/ is a pattern match operator. Perl is very easy to learn. Enter 'H' or 'h' for help.

    Why?

    Your use of split is fine. But you need to loop thru your array:
  • line 6: if it doesn't make sense, figure it out
  • line 7: ditto
  • line 8: ditto