CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
splitting elements in a file and returning values?!

 



bawy
Deleted

Jun 12, 2000, 12:46 AM

Post #1 of 2 (532 views)
splitting elements in a file and returning values?! Can't Post

I am attempting to write a shopping cart system from scratch and got stuck. I have each item append to a file but now I have no idea how to split the elements and return them in scalar or array forms?

Here is the format of the external file that holds the order: (i is the item number and will correspond to more info about the item coded in the perl script, q is quantity, s is the size format of the product, p is price)

i=11 q=7 s=case of 12 boxes p=84.00
i=11 q=7 s=box of 9 bags p=28.00
i=11 q=1 s=case of 12 boxes p=12.00
i=11 q=2 s=case of 12 boxes p=24.00

here is as far as I got before I realized I had no idea what I was doing (this caused an error and is probably all wrong):

open(order, "$host.ord") | | &noorder;
@orders = <order>;
close(order);

foreach $ele (@orders) {
($lkey, $lvalue) = split (/=/, $ele);
}
foreach ele (@orders) {
print "$lkey, $lvalue";
}


japhy
Enthusiast

Jun 12, 2000, 5:48 AM

Post #2 of 2 (532 views)
Re: splitting elements in a file and returning values?! [In reply to] Can't Post

Well, one way would be to do:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


for $element (@array) {
@data = $element =~ /(\w+)=(.*?)(?=\w+=|$)/g;
while (@data) {
($key,$val) = (shift @data, shift @data);
print "$key, $val\n";
}
}
</pre><HR></BLOCKQUOTE>

This creates an array from the key=value pairs in the string "this=that those=mine and yours something=else". The regular expression I use is somewhat difficult to understand, so let me do my best to explain it.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


m{
(\w+) # the 'key' (return this value)
= # then an =
(.*?) # then as little as needed (and return this value)

(?= # that WOULD be followed by...
\w+= # the next key
| # OR
$ # end-of-string
)
}gx; # /g for global, /x for these comments
</pre><HR></BLOCKQUOTE>

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives