CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
read text from file to an array

 



kvok
New User

Jun 30, 2014, 5:32 AM

Post #1 of 12 (845 views)
read text from file to an array Can't Post

Hi,

I need to read following text to an array :
my file contains following line:
abc efg hhg jjja 1331rr

I mean each string should be as one element ?
Iam able to read it but the whole line is one element.

Can you help me with that ?


Laurent_R
Veteran / Moderator

Jun 30, 2014, 10:58 AM

Post #2 of 12 (785 views)
Re: [kvok] read text from file to an array [In reply to] Can't Post

Use the split function to split into individual strings. For example something like this:


Code
my $line = "abc efg hhg jjja 1331rr "; 
my @array = split / /, $line;



bulrush
Novice

Jul 8, 2014, 7:13 AM

Post #3 of 12 (585 views)
Re: [kvok] read text from file to an array [In reply to] Can't Post


Code
use strict; 
use warnings;
my($filename,@a,@lines,$i);

$filename="file.txt"; # Must be in same dir as .pl file.
open(INFILE, $filename) || die "ERROR: Could not open $filename. $!";
@lines=<INFILE>; # Read all lines from file into array.
close(INFILE);
#@a=split(' ',$lines[0]); # Split first line in file on space
@a=split(/ /,$lines[0]); # Split first line in file on space

for ($i=0; $i<=$#a; $i++) # Now print every element in @a.
{
print "$a[$i]\n";
} # For i

-----
* Redhat Linux RHEL 5.5.56
* Perl 5.8.8

(This post was edited by bulrush on Jul 10, 2014, 5:13 AM)


BillKSmith
Veteran

Jul 8, 2014, 8:55 AM

Post #4 of 12 (574 views)
Re: [bulrush] read text from file to an array [In reply to] Can't Post

I can suggest several minor improvements to your style. None of them will affect the output of this script, but they are good habits which could make a difference in the future.

The most important of these is to declare your variables in the smallest possible scope. Declaring them all at the beginning of your file largely defeats the advantage of using strict.

Never use C-style 'for' loops. In this case, it is better not to use a loop at all.

The first argument to split should be a regular expression, not a string. (Look closely at Laurent's example)

The three-argument form of open can improve the diagnostics when things go wrong.

Always use lexical file handles. In simple cases like this it does not make any difference, but it is a good habit which can prevent nasty errors in the future.

The lower precedence form of 'or' can prevent a hard-to-find error in open, especially when parenthesis are not used in the call (The preferred style for built-ins).


Code
use strict;  
use warnings;

my $filename="file.txt"; # Must be in same dir as .pl file.
open my $INFILE, '<', $filename or die "ERROR: Could not open $filename. $!";
my @lines=<$INFILE>; # Read all lines from file into array.
close($INFILE);
my @a=split / /,$lines[0]; # Split first line in file on space

#for my $field (@a) # Now print every element in @a.
# {
# print "$field\n";
# }

print do {local $, = "\n"; "@a\n"};

Good Luck,
Bill


Laurent_R
Veteran / Moderator

Jul 8, 2014, 9:57 AM

Post #5 of 12 (569 views)
Re: [bulrush] read text from file to an array [In reply to] Can't Post

Hello bulrush,

Please don't update silenciously your posts after people made some comments on it. These comments become difficult to understand if what these comments are discussing is no longer there. Or if you feel that you really want to fix something, they do it in such a way as to preserve your original post and show explicitly where you are adding some corrections.


Zhris
Enthusiast

Jul 8, 2014, 11:24 AM

Post #6 of 12 (566 views)
Re: [BillKSmith] read text from file to an array [In reply to] Can't Post

Hi Bill,

Minor correction. I think you meant to use the $" special variable over $,.

Regards,

Chris


BillKSmith
Veteran

Jul 8, 2014, 12:48 PM

Post #7 of 12 (560 views)
Re: [Zhris] read text from file to an array [In reply to] Can't Post

You are right, thanks. I knew that I should have tested. Blush
Good Luck,
Bill


bulrush
Novice

Jul 10, 2014, 5:18 AM

Post #8 of 12 (416 views)
Re: [BillKSmith] read text from file to an array [In reply to] Can't Post

BillKSmith,
I'm just curious to learn anything new.


Code
#@a=split(' ',$lines[0]); # Split first line in file on space  
@a=split(/ /,$lines[0]); # Split first line in file on space


In split(PATTERN, EXPR), the first parameter is a PATTERN, the PATTERN delimiter can be anything, but I can see where always using slashes by default helps readability, and indicates PATTERN can be a regex. Was there another reason why you recommend using slashes?

Also, in the docs here http://perldoc.perl.org/functions/split.html they do use a single quote for PATTERN. That's probably where I got it.
-----
* Redhat Linux RHEL 5.5.56
* Perl 5.8.8

(This post was edited by bulrush on Jul 10, 2014, 5:25 AM)


BillKSmith
Veteran

Jul 10, 2014, 5:55 AM

Post #9 of 12 (391 views)
Re: [bulrush] read text from file to an array [In reply to] Can't Post

I recommended using the format shown in the grammar of split in perlfunc. Note however, the same document uses quotes in some examples. Style guidelines are intended to help. They can (and perhaps should) be ignored for very good reasons.
Good Luck,
Bill


bulrush
Novice

Jul 10, 2014, 6:26 AM

Post #10 of 12 (370 views)
Re: [BillKSmith] read text from file to an array [In reply to] Can't Post

Thank you BillKSmith, your answers are helpful. :)
-----
* Redhat Linux RHEL 5.5.56
* Perl 5.8.8


FishMonger
Veteran / Moderator

Jul 10, 2014, 6:30 AM

Post #11 of 12 (368 views)
Re: [bulrush] read text from file to an array [In reply to] Can't Post

Splitting on the ' ' string is a special case and works differently than splitting on the / / pattern.


Code
#!/usr/bin/perl 

use 5.010;
use strict;
use warnings;
use Data::Dumper;

my $line = " abc efg hhg jjja 1331rr ";

my @pattern = split / /, $line;
my @string = split ' ', $line;

say "split via pattern\n", Dumper \@pattern;
say "split via string\n", Dumper \@string;


c:\test>split.pl

Code
split via pattern 
$VAR1 = [
'',
'abc',
'',
'efg',
'',
'',
'hhg',
'',
'jjja',
'',
'',
'1331rr'
];

split via string
$VAR1 = [
'abc',
'efg',
'hhg',
'jjja',
'1331rr'
];


This behavior is in the documentation.
perldoc -f split
...
...

Code
            As another special case, "split" emulates the default behavior 
of the command line tool awk when the PATTERN is either omitted
or a *literal string* composed of a single space character (such
as ' ' or "\x20", but not e.g. "/ /"). In this case, any leading
whitespace in EXPR is removed before splitting occurs, and the
PATTERN is instead treated as if it were "/\s+/"; in particular,
this means that *any* contiguous whitespace (not just a single
space character) is used as a separator. However, this special
treatment can be avoided by specifying the pattern "/ /" instead
of the string " ", thereby allowing only a single space
character to be a separator. In earlier Perl's this special case
was restricted to the use of a plain " " as the pattern argument
to split, in Perl 5.18.0 and later this special case is
triggered by any expression which evaluates as the simple string
" ".

If omitted, PATTERN defaults to a single space, " ", triggering
the previously described *awk* emulation.



BillKSmith
Veteran

Jul 10, 2014, 7:41 AM

Post #12 of 12 (363 views)
Re: [FishMonger] read text from file to an array [In reply to] Can't Post

Thanks FishMonger, I did not understand that!
Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives