Perl: iterate through multiline match - regex

I would like iterate through a multiline pattern in Perl, but I'm struggling with the syntax.
My input string is:
+++ STAR-WARS 2020-01-01 00:00:00+00:00
S&W #00000000
%%SHOW NAME: Q=Kenobi;%%
RETCODE = 0 Operation success
In-universe information
-----------------------
Species = Human
Gender = Male
television series of num = whatever
(Number of results = 1)
Personal Details
----------------
First Name = Obi-Wan
Last Name = Kenobi
Alias = Padawan
= Jedi Knight
= Jedi General
= Jedi Master
Points to other set of information = whatever
(Number of results = 1)
Other attribute
---------------
Significant other = Satine Kryze
Affiliation = Jedi Order
= Galactic Republic
= Rebel Alliance
Occupation = Jedi
(Number of results = 1)
--- END
My desired resulting hash would be:
$VAR1 = {
'In-universe information' => {
'Gender' => 'Male',
'Species' => 'Human',
'results' => '1',
'television series of num' => 'whatever'
},
'Other attribute' => {
'Affiliation' => [
'Jedi Order',
'Galactic Republic',
'Rebel Alliance'
],
'Occupation' => 'Jedi',
'Significant other' => 'Satine Kryze',
'results' => '1'
},
'Personal Details' => {
'Alias' => [
'Padawan',
'Jedi Knight',
'Jedi General',
'Jedi Master'
],
'First Name' => 'Obi-Wan',
'Last Name' => 'Kenobi',
'Points to other set of information' => 'whatever',
'results' => '1'
},
'code' => '0',
'description' => 'Operation success'
};
What I have come up with works well for a "single block" (e.g. Personal Details above). However, if the data contains multiple blocks, I can't figure out how to iterate through every matching block. (e.g. use while with /g)
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
local $/;
my $output = <DATA>;
my %hash;
($hash{'code'}, $hash{'description'}) = $output =~ /^RETCODE = (\d+)\s+(.*)\n/m;
if ($hash{'code'} eq "0") {
my ($type,$data, $results) = $output =~ /([^\n]+)\n-+\n(.*)\n\n\(Number of results = (\d+)\)\n\n/sm;
my $previousKey = "";
while ($data =~ /(.+)$/mg) {
my $line = $1;
$line =~ s/(?:^ +)//g;
my ($key, $value);
if ($line =~ /^\s*= /) {
($value) = $line =~ /^\s*= (.*)$/;
$hash{$type}{$previousKey} = [ $hash{$type}{$previousKey} ] unless ref($hash{$type}{$previousKey});
push (#{$hash{$type}{$previousKey}}, $value);
} else {
($key, $value) = split(/ = /, $line);
$hash{$type}{$key} = $value;
$previousKey = $key;
}
}
say STDERR Dumper(\%hash);
}
__DATA__
+++ STAR-WARS 2020-01-01 00:00:00+00:00
S&W #00000000
%%SHOW NAME: Q=Kenobi;%%
RETCODE = 0 Operation success
In-universe information
-----------------------
Species = Human
Gender = Male
television series of num = whatever
(Number of results = 1)
Personal Details
----------------
First Name = Obi-Wan
Last Name = Kenobi
Alias = Padawan
= Jedi Knight
= Jedi General
= Jedi Master
Points to other set of information = whatever
(Number of results = 1)
Other attribute
---------------
Significant other = Satine Kryze
Affiliation = Jedi Order
= Galactic Republic
= Rebel Alliance
Occupation = Jedi
(Number of results = 1)
--- END
Few facts:
every "block" always contains a header, followed by newline and dashes equal to the length of the header.
every "block" always ends with \n, followed by (Number of results = \d+), followed by \n.
each key/value pair always have two spaces before and after the equal sign. i.e. / = /
when no key exists, assume it's an [array], and append the value to the previous key. e.g. Alias in my example above.
the string will always ends with --- END followed by a \n

According your description the section is starting with +++ ... and ending with --- END.
Based on this information the input can be devided with regex into blocks of interest which then processed individually in a loop with a parser to build a hash.
NOTE: the parser was slightly modified and put into subroutine
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
my #shows;
my $data = do { local $/; <DATA> };
my #blocks = $data =~ /^(\+\+\+ .*?^--- END)/msg;
push #shows, parse($_) for #blocks;
say Dumper(\#shows);
exit 0;
sub parse {
my $data = shift;
my(#sections,$re,$r);
# Alternative block to extract show info section
# $re = qr/^\+\+\+\s+(\S+)\s+(\S+)\s+(\S+)\s+\S+\s+(\S+)\s+%%[^:]+?:\s+([^;]+?);%%\s+RETCODE = (\d+)\s+([^\n]+)/;
# $r->{info}->#{qw/show day time sw show_name code description/} = $data =~ /$re/;
$re = qr/RETCODE = (\d+)\s+([^\n]+)/;
$r->#{qw/code description/} = $data =~ /$re/;
#sections = $data =~ /\n\n(.+?\n-+.*?\(Number of results = \d+\))/gs;
for my $block ( #sections ) {
my($section,#lines,$key,$value);
#lines = split("\n",$block);
$section = $lines[0];
for my $line (#lines[2..$#lines-2] ) {
$line =~ s/^\s+//;
if( $line =~ /^=\s+(.+)/ ) {
$r->{$section}{$key} = [ $r->{$section}{$key} ] unless ref $r->{$section}{$key} eq 'ARRAY';
push #{$r->{$section}{$key}}, $1;
} else {
($key,$value) = split(/ = /,$line);
$r->{$section}{$key} = $value;
}
}
$r->{$section}{results} = $block =~ /\(Number of results = (\d+)\)/gs;
}
return $r;
}
__DATA__
+++ STAR-WARS 2020-01-01 00:00:00+00:00
S&W #00000000
%%SHOW NAME: Q=Kenobi;%%
RETCODE = 0 Operation success
In-universe information
-----------------------
Species = Human
Gender = Male
television series of num = whatever
(Number of results = 1)
Personal Details
----------------
First Name = Obi-Wan
Last Name = Kenobi
Alias = Padawan
= Jedi Knight
= Jedi General
= Jedi Master
Points to other set of information = whatever
(Number of results = 1)
Other attribute
---------------
Significant other = Satine Kryze
Affiliation = Jedi Order
= Galactic Republic
= Rebel Alliance
Occupation = Jedi
(Number of results = 1)
--- END
+++ STAR-WARS 2020-01-01 00:00:00+00:00
S&W #00000000
%%SHOW NAME: Q=Kenobi;%%
RETCODE = 0 Operation success
In-universe information
-----------------------
Species = Human
Gender = Male
television series of num = whatever
(Number of results = 1)
Personal Details
----------------
First Name = Obi-Wan
Last Name = Kenobi
Alias = Padawan
= Jedi Knight
= Jedi General
= Jedi Master
Points to other set of information = whatever
(Number of results = 1)
Other attribute
---------------
Significant other = Satine Kryze
Affiliation = Jedi Order
= Galactic Republic
= Rebel Alliance
Occupation = Jedi
(Number of results = 1)
--- END
Output
$VAR1 = [
{
'Other attribute' => {
'Significant other' => 'Satine Kryze',
'Occupation' => 'Jedi',
'results' => 1,
'Affiliation' => [
'Jedi Order',
'Galactic Republic',
'Rebel Alliance'
]
},
'Personal Details' => {
'results' => 1,
'First Name' => 'Obi-Wan',
'Alias' => [
'Padawan',
'Jedi Knight',
'Jedi General',
'Jedi Master'
],
'Points to other set of information' => 'whatever',
'Last Name' => 'Kenobi'
},
'code' => '0',
'description' => 'Operation success',
'In-universe information' => {
'television series of num' => 'whatever',
'Gender' => 'Male',
'results' => 1,
'Species' => 'Human'
}
},
{
'Other attribute' => {
'Affiliation' => [
'Jedi Order',
'Galactic Republic',
'Rebel Alliance'
],
'results' => 1,
'Significant other' => 'Satine Kryze',
'Occupation' => 'Jedi'
},
'Personal Details' => {
'First Name' => 'Obi-Wan',
'results' => 1,
'Last Name' => 'Kenobi',
'Alias' => [
'Padawan',
'Jedi Knight',
'Jedi General',
'Jedi Master'
],
'Points to other set of information' => 'whatever'
},
'code' => '0',
'description' => 'Operation success',
'In-universe information' => {
'television series of num' => 'whatever',
'results' => 1,
'Gender' => 'Male',
'Species' => 'Human'
}
}
];

Related

Dynamic If else statement, value for condition is from database

is there a way to make this if else condition:
$searchUserTypeName = UserType::findOrFail(1);
success = true;
$message = '';
$user = new User();
if ($searchUserTypeName->name == "Captain" || $searchUserTypeName->name == "Member") {
$fields = [
'teacher_id' => 'Teacher Id',
'team_id' => 'Team',
'mobile' => 'Mobile',
'launched_date' => 'Launched Date',
'endorsed_date' => 'Endorsed Date'
];
} else if ($searchUserTypeName->name == "Mentor" || $searchUserTypeName->name == "Mentee") {
$fields = [
'teacher_id' => 'Teacher Id',
'team_id' => 'Team',
'skype_id' => 'Skype Id',
'google_hangouts' => 'Google Hangouts',
'graduation_date' => 'Graduation Date',
'launched_date' => 'Launched Date',
'endorsed_date' => 'Endorsed Date'
];
}
foreach ($fields as $key => $field) {
if (!$request->has($key) || $request->{$key} == '') {
$success = false;
$message .= $field . ' is required.<br>';
} else {
$user->{$key} = $request->{$key};
}
}
if (!$success) {
$this->setStatus(400);
$this->setSuccess(false);
$this->setMessage($message);
return $this->sendResponse($fields);
}
$user->save();
to dynamic?
The value Captain, Member, Mentor and Mentee is from a mysql table
if Captain or Member
there is a specific field select that will save on the use tabel
same as for Mentor and Mentee
hope you can help
thanks
You can set method in your related model
User extends Model {
public function isName(...$names)
{
return in_array($this->name, $names);
}
}
if ($user->isName('Captain', 'Member')) {
//
}

Test if a string contains the key of a hash in Perl

I have a string and want to tell if it contains the key of a hash and if it does I would like to print the value of the hash like so:
#!/usr/bin/perl -w
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
if ($str contains a key of %h){
print the value of that key; #i.e v1
}
Whats the best way to do this? (Preferably concise enough to contain in an if statement)
#!/bin/perl -w
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
while (($key, $value) = each %h) {
if (-1 != index($str, $key)) {
print "$value\n";
}
}
If you have to search through multiple strings but have just the one unchanging hash, it might be faster to compile the hash keys into a regexp upfront, and then apply that regexp to each string.
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $hash_keys = qr/${\ join('|', map quotemeta, keys %h) }/;
my #strings = (
"this is a string containing key1\n",
"another string containing key1\n",
"this is a string containing key2\n",
"but this does not\n",
);
foreach my $str (#strings) {
print "$str\n" if $str =~ $hash_keys;
}
In some cases (big hash, keys are words and you don't want them to match sub-words) this could be the right approach:
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1 and key3 but notkey2, at least not alone\n";
while ($str =~ /(\w+)/g) {
my $v = $h{$1};
print "$v\n" if defined $v;
}

Activation form does not fully work

i hope someone can help with this. At one point i thought i had this working but cannot figure out why it is not.
The script below does everything but include the Zend_Json::encode. It saves the user in the database it emails the person a link, however the link does not have the encryption included with it.
thanks for your help!
public function contribjoinAction()
{
$request = $this->getRequest();
$conn = XXX_Db_Connection::factory()->getMasterConnection();
$userDao = XXX_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
$userDao->setDbConnection($conn);
if ($request->isPost()) {
$fullname = $request->getPost('full_name');
$username = $request->getPost('username');
$password = $request->getPost('password');
$password2 = $request->getPost('confirmPassword');
$email = $request->getPost('email');
$islegal = $request->getPost('islegal');
$user = new Core_Models_User(array(
'user_name' => $username,
'password' => $password,
'full_name' => $fullname,
'email' => $email,
'is_active' => 0,
'created_date' => date('Y-m-d H:i:s'),
'logged_in_date' => null,
'is_online' => 0,
'role_id' => 2,
'islegal' => $islegal,
));
$id = $userDao->add($user);
$templateDao = XXX_Model_Dao_Factory::getInstance()->setModule('mail')->getTemplateDao();
$templateDao->setDbConnection($conn);
$template = $templateDao->getByName(Mail_Models_Template::TEMPLATE_ACTIVATE_CONTRIBUTOR);
if ($template == null) {
$message = sprintf($this->view->translator('auth_mail_template_not_found'), Mail_Models_Template::TEMPLATE_ACTIVATE_CONTRIBUTOR);
throw new Exception($message);
}
$search = array(Mail_Models_Mail::MAIL_VARIABLE_EMAIL, Mail_Models_Mail::MAIL_VARIABLE_USERNAME);
$replace = array($user->email, $user->user_name);
$subject = str_replace($search, $replace, $template->subject);
$content = str_replace($search, $replace, $template->body);
/**
* Replace the reset password link
* #TODO: Add security key?
*/
$encodedLink = array(
'email' => $email,
'user_name' => $username,
);
$encodedLink = base64_encode(urlencode(Zend_Json::encode($encodedLink)));
$link = $this->view->serverUrl() . $this->view->url(array('encoded_link' => $encodedLink), 'core_user_emailactivate');
$content = str_replace('%activate_link%', $link, $content);
/**
* Get mail transport instance
*/
$transport = Mail_Services_Mailer::getMailTransport();
$mail = new Zend_Mail();
$mail->setFrom($template->from_mail, $template->from_name)
->addTo($user->email, $user->user_name)
->setSubject($subject)
->setBodyHtml($content)
->send($transport);
if ($id > 0) {
$this->_helper->getHelper('FlashMessenger')
->addMessage($this->view->translator('user_join_success'));
$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'core_user_contribjoin'));
}
}
}
I have found the error. I somehow did not put the variable encoded_link into the .ini file for that module under routes.

Add Netsuite Sales order items

I am getting this type of error:
=> i am getting error in the integration of the netsuite.
In sales order add the items in the netsuite so there are some error is define in above section my code is below please see the code add how to solve this problem.
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERRORi am gatting this type of error please help me
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERROR
my code is
include('NetSuiteService.php');
$service = new NetSuiteService();
if($order_items->netsuitid > 0){
$internal_Id = $order_items->netsuitid;
$emailCustomer = $order_items->user_email;
}
else{
$customer_Info = $order->get_customer_info($order->user_id);
$customer_information = array();
foreach($customer_Info as $customer_key => $customer_value){
if($customer_value->meta_key == 'first_name'){
$customer_information['first_name'] = $customer_value->meta_value;
}
if($customer_value->meta_key == 'last_name'){
$customer_information['last_name'] = $customer_value->meta_value;
}
}
$customer_information['email'] = $customer_Info->user_email;
//Add customer into net suit integration
$service = new NetSuiteService();
$customer = new Customer();
$customer->lastName = $customer_information['last_name'];
$customer->firstName = $customer_information['first_name'];
$customer->companyName = 'Company Name';
$customer->phone = '2222222222';
$customer->email = $customer_information['email'];
$emailCustomer = $customer_information['email'];
$request = new AddRequest();
$request->record = $customer;
$addResponse = $service->add($request);
if (!$addResponse->writeResponse->status->isSuccess) {
echo "You are already Registered with Netsuit.";
}
else {
$internal_Id = $addResponse->writeResponse->baseRef->internalId;
$order->insert_Customer($internal_Id,$order->user_id);
}
//End customer into net suit integration
}
//Add Product Information
/*$items = array();
foreach ( $order_items as $item_id => $item ) {
$itemRef = new nsRecordRef(array('internalId'=>$internal_Id));
$qty = $item['qty'];
if($item['type'] == 'line_item'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
if($item['type'] == 'fee'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
$SalesOrderItem->setFields($salesOrderItemFieldArray);
$items[] = $SalesOrderItem;
}
$salesOrderItemList = new nsComplexObject("SalesOrderItemList");
$salesOrderItemList->setFields(array(
"item" => $items
));
$salesOrderFields = array(
"orderStatus" => $order->status,
"entity" => '',
"getAuth" => true,
"shippingCost" => $order->order_shipping,
"shipMethod" => $order->payment_method,
"toBeEmailed" => true,
"email" => $emailCustomer,
"itemList" => $salesOrderItemList
);*/
$so = new SalesOrder();
//created Date
//$so->createdDate = $order->order_date;
//entity
$so->entity = new RecordRef();
$so->entity->internalId = $internal_Id;
$so->entity->name = $order->order_custom_fields['_billing_company'][0];
//Transaction Id
//$so->tranId = $order->order_custom_fields['Transaction ID'][0];
//Transaction Paid Date
//$so->tranDate = $order->order_custom_fields['_paid_date'][0];
//Source
$so->source = 'littlecrate';
//Created From
$so->createdFrom = 'littlecrate.com';
//Currency Name
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->currency = $order->order_custom_fields['_order_currency'];
$so->currencyName = $geoplugin->countryName;
$so->currency = $order->order_custom_fields['_order_currency'][0];
//Discount
$so->discountRate = $order->order_custom_fields['_order_discount'][0];
//Tax
$so->taxRate = $order->order_custom_fields['_order_tax'][0];
//email
$so->email = $order->billing_email;
//Status
//$so->orderStatus = $order->status;
//Billing Address
$so->billAddressList = array(
'billFirstname' => $order->order_custom_fields['_billing_first_name'][0],
'lastname' => $order->order_custom_fields['_billing_last_name'][0],
'billAddressee' => $order->order_custom_fields['_billing_address_1'][0],
'billAddr1' => $order->order_custom_fields['_billing_address_2'][0],
'billCountry' => $order->order_custom_fields['_billing_country'][0],
'billState' => $order->order_custom_fields['_billing_state'][0],
'billZip' => $order->order_custom_fields['_billing_postcode'][0],
'billPhone' => $order->order_custom_fields['_billing_phone'][0],
'billEmail' => $order->order_custom_fields['_billing_email'][0]);
//Shipping Address
$so->shipAddressList = array(
'shipFirstname' => $order->order_custom_fields['_shipping_first_name'][0],
'shipLastname' => $order->order_custom_fields['_shipping_last_name'][0],
'shipAddressee' => $order->order_custom_fields['_shipping_address_1'][0],
'shipAddr1' => $order->order_custom_fields['_shipping_address_2'][0],
'shipCity' => $order->order_custom_fields['_shipping_city'][0],
'shipState' => $order->order_custom_fields['_shipping_state'][0],
'shipZip' => $order->order_custom_fields['_shipping_postcode'][0],
'shiplPhone' => $order->order_custom_fields['_billing_phone'][0],
'shipEmail' => $order->order_custom_fields['_billing_email'][0]);
//Ship Date
//$so->shipDate = $order->order_custom_fields['Transaction ID'][0];
//Shipping Method
$so->shipMethod = $order->shipping_method;
//Shipping Charges
$so->shippingCost = $order->order_shipping;
//Shipping Tax Rate
$so->shippingTax1Rate = $order->order_shipping_tax;
//Payment Method
$so->paymentMethod = $order->payment_method;
//Sub Total
//$so->subTotal = $order->order_total;
//Discount Total(Cart Total)
//$so->discountTotal = $order->cart_discount;
//Tax Total
//$so->taxTotal = $order->order_tax;
//Total
//$so->total = $order->order_total;
//Product Listing
$arrItemsList = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
if($valueProduct['type'] == 'line_item'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
if($valueProduct['type'] == 'fee'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
$i++;
}
//print_r($arrItemsList);
$so->itemList->item = $arrItemsList;
/*$so->itemList = new SalesOrderItemList();
$soi = new SalesOrderItem();
$soi->item = new RecordRef();
$soi->item->internalId = 15;
$soi->quantity = 3;
$soi->price = new RecordRef();
$soi->price->internalId = $id;
$soi->amount = 55.3;
$so->itemList->item = array($soi);*/
$request = new AddRequest();
$request->record = $so;
//print_r($request);
$addResponse = $service->add($request);
print_r($addResponse);
exit;
if (!$addResponse->writeResponse->status->isSuccess) {
echo "ADD ERROR";
} else {
echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
}
+
I Complited Using The Help Of Saqib,
http://stackoverflow.com/users/810555/saqib
He is The Great Developer And Regarding Netsuite Information Please Contact To Saqib Thanks Man U Just Do It.
<?php
$order_date = date('Y-m-d H:i:s');
// create array of fields
$itemArr = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
//if you not have internal id of item in netsuuite then please add the item in the netsuite and try.
$netsuiteItemId = 'Your Item Internal id Which is in the Netsuite Item';
$itemArr[$i]['item']['internalId'] = $netsuiteItemId;
$itemArr[$i]['quantity'] = $valueProduct['qty'];
$i++;
}
if (!define('LF', "\n")) {
define('LF', "\n");
}
/* for use in formatting custom addresses since NetSuite converts to <br> */
//Billing Address Information
/* this example has the customer address info in a db record, just pulled into $row */
$billAddress = stripslashes($order->order_custom_fields['_billing_first_name'][0]) . ' ' . $order->order_custom_fields['_billing_last_name'][0] . LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_1'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_2'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_country'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_state'][0]) . ' - ' . $order->order_custom_fields['_billing_postcode'][0] . ', ' . LF;
$billAddress .= $order->order_custom_fields['_billing_phone'][0] . ', ' . $order->order_custom_fields['_billing_email'][0];
//Shipping Address Information
$shipAddress = stripslashes($order->order_custom_fields['_shipping_first_name'][0]) . ' ' . $order->order_custom_fields['_shipping_last_name'][0] . LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_1'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_2'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_city'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_state'][0]) . ', ' . $order->order_custom_fields['_shipping_postcode'][0] . ', ' . LF;
$shipAddress .= $order->order_custom_fields['_billing_phone'][0] .', '. $order->order_custom_fields['_billing_email'][0];
$purchaseOrderFields = array (
'entity' => array ('internalId' => $internal_Id, 'type' => 'customer'),
'shippingCost' => $order->order_shipping,
'shipMethod' => $order->payment_method,
'toBeEmailed' => true,
//'tranId' => $order->order_custom_fields['Transaction ID'][0],
//'tranDate' => date('Y-m-d H:i:s'),
'source' => 'littlecrate',
'createdFrom' => 'littlecrate.com',
'discountRate' => $order->order_custom_fields['_order_discount'][0],
'taxRate' => $order->order_custom_fields['_order_tax'][0],
'email' => $order->billing_email,
//'shipDate' => date('Y-m-d H:i:s'),
'shipMethod' => $order->shipping_method,
'shippingCost' => $order->order_shipping,
'shippingTax1Rate' => $order->order_shipping_tax,
'paymentMethod' => $order->payment_method,
//'taxTotal' => $order->order_tax,
//'total' => $order->order_total,
'billAddress' => $billAddress,
'shipAddress' => $shipAddress,
'itemList' => array (
'item' => $itemArr
)
);
$salesOrder = new nsComplexObject('SalesOrder');
$salesOrder ->setFields($purchaseOrderFields);
$addResponse = $myNSclient->add($salesOrder );
if (!$addResponse->isSuccess) {
echo "Order Information is Not Inserted Into The Netsuite. Please Contact to Administration.";
exit;
}
?>
You item List object doesn't seem in correct format. Your code should look like this
$itemArr = array();
foreach($order_items_product as $keyProduct =>$valueProduct){
$item = new SalesOrderItem();
$item->item = $valueProduct['product_id'];
$item->quantity = $valueProduct['qty'];
$itemArr[] = $item;
}
$itemList = new SalesOrderItemList();
$itemList->item = $itemArr;
$so->itemList->item = $itemList;

Perl Regex for zero or one match

Below are the two strings-
12/31/2011 05:34:27;U;11.comp;host=win workgroup=home username=bob cmemory=1325133456 qmemory=1325133456 smemory=1325133456 uptime=1325289867
12/31/2011 01:09:20;D;12.comp;host=win workgroup=home username=sam cmemory=1325151687 qmemory=1325151687 smemory=1325151687 uptime=1325228636 session=4677 downtime=1325270175 Exit_status=0
From above strings I want to pick host, workgroup, username, uptime and downtime values using Regex in Perl.
Below is my Perl script-
foreach $line (<FILE>) {
if($line =~ m<\d{2}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2};[U|D].*host=(\w+)\s+workgroup=(\w+)\s+hostname=(\w+)\s+.*uptime=(\d+)\s+.*(downtime=)?(\d*)>){
my $host = $1;
my $workgroup = $2;
my $hostname = $3;
my $uptime = $4;
my $downtime = $5;
print "host=$host workgroup=$workgroup hostname=$hostname uptime=$uptime downtime=$downtime\n";
}
}
The only problem, I am facing here is because of downtime. This attribute may not be present in the line. I am not able to pick this field properly.
Why not use split instead? Then you could add the various categories to a hash, like so:
use strict;
use warnings;
use Data::Dumper;
while (<DATA>) {
my ($date, $foo, $bar, $data) = split /;/, $_, 4;
my %data = map { split /=/ } split ' ', $data;
print Dumper \%data;
}
__DATA__
12/31/2011 05:34:27;U;11.comp;host=win workgroup=home username=bob cmemory=1325133456 qmemory=1325133456 smemory=1325133456 uptime=1325289867
12/31/2011 01:09:20;D;12.comp;host=win workgroup=home username=sam cmemory=1325151687 qmemory=1325151687 smemory=1325151687 uptime=1325228636 session=4677 downtime=1325270175 Exit_status=0
Output:
$VAR1 = {
'workgroup' => 'home',
'cmemory' => '1325133456',
'qmemory' => '1325133456',
'uptime' => '1325289867',
'smemory' => '1325133456',
'username' => 'bob',
'host' => 'win'
};
$VAR1 = {
'qmemory' => '1325151687',
'Exit_status' => '0',
'smemory' => '1325151687',
'username' => 'sam',
'host' => 'win',
'workgroup' => 'home',
'cmemory' => '1325151687',
'session' => '4677',
'downtime' => '1325270175',
'uptime' => '1325228636'
};
If you now want to refer to the "downtime" value, you can do something such as:
my $downtime = $hash{downtime} // "N/A";
Where // is the defined-or operator, somewhat preferred here over logical or ||.