Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl parsing a string where segment missing 2

Status
Not open for further replies.

jcarrott

Programmer
May 28, 2009
130
0
0
US
I am parsing a series of lines and sometimes the segment is not there, but I have to return a single space for the position.

My current code is

# segin[6] is N3 - Bill to Address
@line = split(/\^/, $segin[6]);
$bt_add1 = substr($line[1], 0, 31);
$bt_add2 = substr($line[2], 0, 31);

Here is a sample of the data.

~N3^1514 JEFFERSON HWY~N4

For this example there is no $line[2], there are other cases where there is no segin[6] so I want to default a space.

Is this possible?
 
You can't to $bt_add1 or $bt_add2 if @line does not have value, which means $segin[6] has to exist, correct?

UNTESTED:

if (defined $segin[6]) {# note: u can use something other than define like a pattern match or something as define might be depricated in new releases of perl.
#assupmtion is that $line[1] has to exist at this point and you're concern is only $line[2].

$line[2] ~= /somePattern/ : ($bt_add2=substr...) ? ($bt_add2=" ");
} else {
print " ";
}
 
The problem is that there will be a segment[6], but there might not be a $line[1] or $line[2]
 
You're not using $line[0] so I'm assuming that @line will have some data in it always.

$line[1] and $line[2] are part of the same array so you can check the size of the array and see if has more than 1 element in it.

or you can do the same check for $line[1], as listed in my pervious post for $line[2].
 
So I could use

$line[2] ~= (length($line[2] > 1) : ($bt_add2=substr...) ? ($bt_add2=" ");

To make sure that if the array element empty, I would fill $bt_add2 with a space. Is this correct?
 
Well, your code is incorrect, but the principle is OK. Should be written
Code:
$bt_add2=$line[2]?substr($line[2],0,31):'';
This code won't produce a warning if $line[2] is not present; don't know however why you test for [tt]length>1[/tt] .
Concerning [tt]$line[1][/tt] being not present, this should be signaled by two consecutive carets, unless [tt]$line[2][/tt] is also not present.

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
prex1,

Thanks for that, I had a moment there.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top