Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Splitting multiple patterns

by stevieb (Canon)
on Apr 09, 2012 at 04:11 UTC ( [id://964075]=note: print w/replies, xml ) Need Help??


in reply to Splitting multiple patterns

You could split the line the first time at the space, assigning the name as the first side of the whitespace and put the rest into another variable, then split the $rest variable on the commas:

#!/usr/bin/perl use warnings; use strict; open my $fh, "<", "infos.txt" or die "cannot open infos.txt: $!"; while ( my $line = <$fh> ){ chomp $line; my ( $name, $rest ) = split /\s+/, $line; my ( $age, $gender, $address ) = split /,/, $rest; print "Name: $name\n"; print "Age: $age\n"; print "Gender: $gender\n"; print "Address: $address\n"; print "\n"; }

Output:

Name: Mawts Age: 25 Gender: female Address: melbourne Name: Awts Age: 24 Gender: male Address: sydney

Replies are listed 'Best First'.
Re^2: Splitting multiple patterns
by astronogun (Sexton) on Apr 09, 2012 at 04:35 UTC
    Hi stevieb

    How about if I put the infos.txt file into a array first and then splitting it from there. like first it will open the .txt file then putting it in a array, then split them inside..

    open(INFILE, "<", "infos.txt") or die ("cannot open input: $!"); my @infos = <INFILE>; chomp(@infos);

    How can I split the datas on my @infos? thanks

      It's really not much different. However, slurping in the whole file can run you out of memory if your file is very large.

      #!/usr/bin/perl use warnings; use strict; open my $fh, "<", "infos.txt" or die "cannot open infos.txt: $!"; my @array = <$fh>; close $fh; for my $line ( @array ){ chomp $line; my ( $name, $rest ) = split /\s+/, $line; my ( $age, $gender, $address ) = split /,/, $rest; print "Name: $name\n"; print "Age: $age\n"; print "Gender: $gender\n"; print "Address: $address\n"; print "\n"; }
        Hi stevieb,

        One last question. How about if want to get only the $address? and only print the "Address:"? What I want is to split the Name up to Gender so that it will only read the $address

        Thanks

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://964075]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-04-23 14:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found