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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Several Problems working with strings 2

Status
Not open for further replies.

TSch

Technical User
Jul 12, 2001
557
DE
Hi everyone,

could you help me out again ?

Let's say I got the following strings stored in a file input.txt :

Code:
Value1 Value2   Value3     Value4
Value5  Value6     Value7  Value8

First I tried to read all the values into an array:

Code:
open (IN1, "input.txt");
@values = <IN1>;
foreach (@values)
{
print "Here is a single value: ", $_, "\n":
}

But this gave me only 2 values:

Code:
Here is a single value: Value1 Value2   Value3     Value4
Here is a single value: Value5  Value6     Value7  Value8

Next I changed it to scalar reading:

Code:
open (IN1, "input.txt");
while (<IN1>)
{
print "Here is a single value: ", $_, "\n":
}

Same output ...

Code:
Here is a single value: Value1 Value2   Value3     Value4
Here is a single value: Value5  Value6     Value7  Value8

How can I solve this problem ?
What if the value separator is not a blank but something else (e.G. a ; or a -) ?

Best Regards,
Thomas
 
Hi

What is your goal ? Something like this ?
Code:
Here is a single value: Value1
Here is a single value: Value2
[silver]...[/silver]
Here is a single value: Value8

That will not be so easy in Perl as it looks. Perl supports only fixed strings as record separator, so you can not just split the record on any whitespace characters :
man perlvar said:
Remember: the value of [tt]$/[/tt] is a string, not a regex. awk has to be better for something. [ignore]:)[/ignore]

Personally I would slurp in the file in one piece then [tt]split[/tt] it "manually" :
Perl:
[b]open[/b] IN1[teal],[/teal] [green][i]"input.txt"[/i][/green][teal];[/teal]
[b]undef[/b] [navy]$/[/navy][teal];[/teal]

[b]foreach[/b] [teal]([/teal][b]split[/b] [green][i]/\s+/[/i][/green][teal],[/teal] [green][i]<IN1>[/i][/green][teal])[/teal] [teal]{[/teal]
  [b]print[/b] [green][i]"Here is a single value: "[/i][/green][teal],[/teal] [navy]$_[/navy][teal],[/teal] [green][i]"\n"[/i][/green][teal];[/teal]
[teal]}[/teal]


Feherke.
[link feherke.github.com/][/url]
 
feherke, [tt]split[/tt] without parameters splits the [tt]$_[/tt] variable on multiple spaces. So this should work:
Code:
while(<IN1>){
  push @values,split;
}
for(@values){
  print "Here is a single value: ", $_, "\n":
}

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Thanks a lot for the help everyone !
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top