snoofkin
snoofkin

Reputation: 8895

Perl Arrays and grep

I think its more a charachters, anyway, I have a text file, consisted of something like that:

COMPANY NAME

    City

    Addresss,
     Address number

    Email 

    phone number

and so on... (it repeats itself, but with different data...), lets assume thing text is now in $strting variable.

I want to have an array (@row), for example:

$row[0] = "COMPANY NAME";
$row[1] = "City";
$row[2] = "Addresss,
              Address number";
$row[3] = "Email";
$row[4] = "phone number";

At first I though, well thats easily can be done with grep, something like that: 1) @rwo = grep (/^^$/, $string); No GO! 2) @row = grep (/\n/, $string);

still no go, tried also with split and such, still no go. any idea? thanks,

Upvotes: 1

Views: 683

Answers (4)

Zaid
Zaid

Reputation: 37136

grep cannot take a string as an argument.

This is why you need to split the string on the token that you're after (as FM shows).

While it isn't clear what you need this for, I would strongly recommend considering the Tie::File module:

Upvotes: 0

Nikhil Jain
Nikhil Jain

Reputation: 8332

use strict;
 use warnings;
 my $string = "COMPANY NAME

        City

        Addresss,
         Address number

        Email

        phone number";

    my @string_parts = split /\n\n+/, $string; 
    foreach my $test (@string_parts){
          print"$test\n";
    }

OUTPUT:

COMPANY NAME
City
Addresss,
Address number 
Email
phone number

Upvotes: 1

Dave Cross
Dave Cross

Reputation: 69224

FM has given an answer that works using split, but I wanted to point out that Perl makes this really easy if you're reading this data from a filehandle. All you need to do is to set the special variable $/ to an empty string. This puts Perl into "paragraph mode". In this mode each record returned by the file input operator will contain a paragraph of text rather than the usual line.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

local $/ = '';

my @row = <DATA>;

chomp @row;

print Dumper(\@row);

__DATA__
COMPANY NAME

City

Addresss,
 Address number

Email 

phone number

The output is:

$ ./addr 
$VAR1 = [
          'COMPANY NAME',
          'City',
          'Addresss,
 Address number',
          'Email ',
          'phone number'
        ];

Upvotes: 6

FMc
FMc

Reputation: 42411

The way I understand your question, you want to grab the items separated by at least one blank line. Although /\n{2,}/ would be correct in a literal sense (split on one or more newlines), I would suggest the regex below, because it will handle nearly blank lines (those containing only whitespace characters).

use strict;
use warnings;

my $str = 'COMPANY NAME

City

Addresss,
 Address number

Email 

phone number';

my @items = split /\n\s*\n/, $str;

Upvotes: 5

Related Questions