in reply to regex to split a line

Howdy :)

Just reading between the lines a little... if you are going to store this stuff in a hash, then I'm guessing that at some later stage you'll want to use the information in the hash. At which time you'll probably need to separate out the different user "attributes" (Real Name, email, etc).

So, why not do this at the start?

Because your data appears to be quite well formed, then using split seems the natural way to go, and create a HoH. Something like this:

#!/usr/bin/perl -w use strict; my %user_info; while (<DATA>) { chomp; my ($user, $attribs) = $_ =~ m/^(\S+)\s+(.+)$/; my ($realname, $email, $foo, $bar, undef) = split /\|/, $attribs; $user_info{$user}{'Real Name'} = $realname; $user_info{$user}{'Email'} = $email; $user_info{$user}{'Foo'} = $foo; $user_info{$user}{'Bar'} = $bar; } __DATA__ username Real Name|email@gmail.com|2|30| fred Fred Bloggs|fbloggs@gmail.com|3|27| harryp Harry Potter|harry@gmail.com|5|32|

You could then do something like this:

foreach my $user (keys %user_info) { print "Username:$user Real Name:$user_info{$user}{'Real Name'}\n"; }

Which would give you:

Username:harryp Real Name:Harry Potter Username:fred Real Name:Fred Bloggs Username:username Real Name:Real Name

Note that the above code could be shortened significantly, but I've deliberately kept it verbose so that it's obvious what's going on. It also doesn't include any sanity-checking on your data, but that could easily be added in.

Hope this helps,
Darren :)

Replies are listed 'Best First'.
Re^2: regex to split a line
by davorg (Chancellor) on Jun 21, 2006 at 08:40 UTC

    This looks to me like a good opportunity to use a hash slice.

    use strict; use warnings; my %user_info; my @fields = qw(name email foo bar); while (<DATA>) { chomp; my ($user, $attribs) = split /\s+/, $_, 2; my %record; @record{@fields} = split /\|/, $attribs; $user_info{$user} = \%record; } foreach my $user (keys %user_info) { print "Username:$user Real Name:$user_info{$user}{name}\n"; }
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg