I am using a 3rd party shopping cart solution that runs on a server (SellerDeck). I have some code that runs on the server to format a shopping basket with basic product data (quantity, price, name). I need to find some more data which I think is held in 2 arrays of hashes. I dont know what is contained in these 2 arrays so I would like to convert the array to a string and output via the existing code that puts it in a cookie on the client which I can then view. The 2 arrays are $pCartItem and $pProduct (see code at the bottom for how they are used).
The string $cartStr (bottom of the code) is output onto the client in a cookie by another part of the code.
I would like to covert the 2 arrays into 2 strings which can be concatenated onto $cartStr. I can then read the contents on my local pc (client). My issue is I am very unfamiliar with perl and know how to do the conversion.
I tried adding :
my $MiniCrtS=" ";
my $MiniCartElmt;
foreach $MiniCartElmt (#{$pProduct}) {
$MiniCrtS=$MiniCrtS . $MiniCartElmt;
}
and then changed the $cartStr from:
HTML::Entities::encode(substr($pProduct->{'NAME'},0,$abrv))
to:
HTML::Entities::encode(substr($MiniCrtS,0,$abrv))
but this change makes the code crash when run.
Any ideas on what I am doing wrong or an alternative to find out the data in the arrays?
Many thanks Tony
The relevant code is:
sub miniCart
{
use HTML::Entities ();
my $Self = shift;
my $abrv=12; # number of characters to abbreviate item name
my $defaultCur="£"; # currency symbol to include
my $cartStr="ss=" . $::g_sSearchScript . "cur=" . $defaultCur;
my $pCartItem;
foreach $pCartItem (#{$Self->{_CartList}})
{
my ($Status, $Message, $pProduct) = GetProduct($pCartItem->{'PRODUCT_REFERENCE'}, $pCartItem->{'SID'});
if ($Status == $::FAILURE)
{
return ($Status, $Message, []);
}
elsif ($Status == $::NOTFOUND)
{
next;
}
my #Prices = $Self->GetCartItemPrice($pCartItem);
$cartStr=$cartStr . "&!" . $pCartItem->{'QUANTITY'} . "x" . HTML::Entities::encode($pCartItem->{'PRODUCT_REFERENCE'}) . ">" . HTML::Entities::encode(substr($pProduct->{'NAME'},0,$abrv)) . ">" . $Prices[2]/100;
}
return $cartStr;
}
To get a dump of a data structure, you can use Data::Dumper.
I'd use it as follows:
use Data::Dumper qw( );
sub dumper {
local $Data::Dumper::Indent = 0;
local $Data::Dumper::Sortkeys = 1;
local $Data::Dumper::Terse = 1;
local $Data::Dumper::Useqq = 1;
return Data::Dumper::Dumper($_[0]);
}
warn("pProduct: " . dumper($pProduct));
This will log it the string produced to the web server's error log, but you could also return it in a cookie if that's what you really want.
Related
I am working on a database project, where I want to create an array as follows:
unsigned char* drillSize[][10] = {
{"0.3678", "23.222", "MN", "89000", ".000236", "678", "ZX", "8563", "LX", "0.678"},
{"0.3678", "23.222", "MN", "89000", ".000236", "678", "ZX", "8563", "LX", "0.678"},
.
.
.
//around 6000 rows }
I have been provided with this data in an Microsoft Word file. If I were to key in the data manually it might take weeks; is there a way to insert commas and inverted commas for each element by some means?
You can try it with regular expressions.
If your data is structured in any way like a csv file you can just import it into your program in some way and then slice it up with basic string functions.
In php I'd
$input = file_get_contents($myfile) //lets say this contains a text: 1,2,3,4,5
$sliced = explode(",",$input);
$myarray = null; //our variable
$output = "\$myarray = new array("; //creating a template for an array as a String
//some logic with the $sliced array if you need
...
$output .= implode(",",$sliced); //we put it back as string
$output .= ");"; //close the array
eval($output); //after this its in php's scope
print_r($myarray);
Basically that's what you need in a more complex form. If the text is not that structured you might need some regular expression library for C, but I'd recommend creating a text in Python, Perl or something which has more support and more flexible then copy the code manually back to C.
Again, a whole day and I am stuck again.
I need to use an array of words or var that contains forbidden words that cannot appear in an email address.
Either:
$baddies = 'smtp mailer sysop';
or
#baddies = qw(smtp mailer sysop);
or
#baddies = qw/smtp mailer sysop/;
There are more bad words in the array too, about two dozen.
I am not running the latest version of perl so ~~ and so on are not supported.
I have a loop going on that sends the bands schedule out.
In that loop I need to check to see if the email contains any of those words.
I realize there may be some good emails that contain a match but, that is fine.
I have tried literally dozens of examples after I gave up trying to figure it out.
Latest was:
####FYI## $uaddress is from the foreach $uaddress(#addresses){ loop.
my %params = map { $uaddress => 1 } #baddies;
if(exists($params{$uaddress})) {
print "yep, it's there"; #for testing
push(#failed,"$uaddress is restricted<br />");
But, everything I tried just does not do what I need.
I even tried =~ and so on.
I AM REALLY feeling stupid about now..
I need another lesson here folks.. Thanks in advance.
Update: I also tried:
$baddies = 'smtp mailer sysop';
my #baddies = split / /, $baddies;
# iterate through the array
foreach (#baddies) {
if($_ =~ $uaddress) #I also reversed that {
print qq~$uaddress contains $_~;
}
}
Through trial, error and dumb luck, I haphazardly got this below to work:
foreach $uaddress(#addressList) {
$uaddress =~ s/\s//g;
#baddies = qw(smtp mailer sysop);
my #failed;
foreach (#baddies) {
if($uaddress =~ m/$_/i) {
push(#failed,"$uaddress is restricted because it found \"$_\" in the address<br />");
}
}
##stuff happens with emails that passed like Email::Verify
}
In hook_user_update I'm retrieving a facebook profile pic and saving a record in the file_managed table. That much is going well. But I also want to save a record for a file field attached to the user entity. Normally what I do in these hooks is assign the values to $edit['field_something'], and I think that's the correct way to do this. That has always worked for other field types, but it is not working for the file field. You can see toward the end of the function where I dump the vars to confirm that I have something suitable to assign to $edit['field_something'] -- at least, I think it's suitable. I get no errors, but no record is created in the field_data_field_image table. What am I missing? Thank you!
/**
* Implementation of hook_user_update().
*
*/
function hifb_user_update(&$edit, $account, $category) {
if (empty($account->field_image['und'])) {
$fbid = $edit['field_facebook_id']['und'][0]['value'];
if (!empty($fbid)) {
$url = 'http://graph.facebook.com/' . $fbid . '/picture?type=large';
if ($file_contents = file_get_contents($url)) {
$size = getimagesize($url);
$ext = image_type_to_extension($size[2]);
$filename = 'fb_' . $fbid . '_u_' . $account->uid . $ext;
$uri = file_default_scheme() . '://' . $filename;
// Saves the file to the default files directory and creates the record in files_managed table.
$file = file_save_data($file_contents, $uri, FILE_EXISTS_REPLACE);
//var_dump($file); die;
/* Here's an example from the var_dump: object(stdClass)#120 (8) { ["fid"]=> string(3) "576" ["uri"]=> string(30) "public://fb_767816596_u_1.jpeg" ["filename"]=> string(21) "fb_767816596_u_1.jpeg" ["filemime"]=> string(10) "image/jpeg" ["uid"]=> string(1) "1" ["status"]=> int(1) ["timestamp"]=> int(1339686244) ["filesize"]=> int(2919) } */
// Creates record in field_data_field_image table??
$edit['field_image']['und'][0] = (array)$file;
}
}
}
}
I believe the reason it doesn't work is because in hook_user_update, the update has already occurred. So setting a value for $edit has no effect. The same code that I posted in the question works fine in hook_user_presave.
I have an array of hash references. The hashes contain 2 keys, USER and PAGES. The goal here is to go through the array of hash references and keep a running total of the pages that the user printed on a printer (this comes from the event logs). I pulled the data from an Excel spreadsheet and used regexes to pull the username and pages. There are 182 rows in the spreadsheet and each row contains a username and the number of pages they printed on that job. Currently the script can print each print job (all 182) with the username and the pages they printed but I want to consolidate this down so it will show: username 266 (i.e. just show the username once, and the total number of pages they printed for the whole spreadsheet.
Here is my attempt at going through the array of hash references, seeing if the user already exists and if so, += the number of pages for that user into a new array of hash references (a smaller one). If not, then add the user to the new hash ref array:
my $criteria = "USER";
my #sorted_users = sort { $a->{$criteria} cmp $b->{$criteria} } #user_array_of_hash_refs;
my #hash_ref_arr;
my $hash_ref = \#hash_ref_arr;
foreach my $index (#sorted_users)
{
my %hash = (USER=>"",PAGES=>"");
if(exists $index{$index->{USER}})
{
$hash{PAGES}+=$index->{PAGES};
}
else
{
$hash{USER}=$index->{USER};
$hash{PAGES}=$index->{PAGES};
}
push(#hash_ref_arr,{%hash});
}
But it gives me an error:
Global symbol "%index" requires explicit package name at ...
Maybe my logic isn't the best on this. Should I use arrays instead? It seems as though a hash is the best thing here, given the nature of my data. I just don't know how to go about slimming the array of hash refs down to just get a username and the total pages they printed (I know I seem redundant but I'm just trying to be clear). Thank you.
my %totals;
$totals{$_->{USER}} += $_->{PAGES} for #user_array_of_hash_refs;
And then, to get the data out:
print "$_ : $totals{$_}\n" for keys %totals;
You could sort by usage too:
print "$_ : $totals{$_}\n" for sort { $totals{$a} <=> $totals{$b} } keys %totals;
As mkb mentioned, the error is in the following line:
if(exists $index{$index->{USER}})
However, after reading your code, your logic is faulty. Simply correcting the syntax error will not provide your desired results.
I would recommend skipping the use of temporary hash within the loop. Just work with the a results hash directly.
For example:
#!/usr/bin/perl
use strict;
use warnings;
my #test_data = (
{ USER => "tom", PAGES => "5" },
{ USER => "mary", PAGES => "2" },
{ USER => "jane", PAGES => "3" },
{ USER => "tom", PAGES => "3" }
);
my $criteria = "USER";
my #sorted_users = sort { $a->{$criteria} cmp $b->{$criteria} } #test_data;
my %totals;
for my $index (#sorted_users) {
if (not exists $totals{$index->{USER}}) {
# initialize total for this user
$totals{$index->{USER}} = 0;
}
# add to user's running total
$totals{$index->{USER}} += $index->{PAGES}
}
print "$_: $totals{$_}\n" for keys %totals;
This produces the following output:
$ ./test.pl
jane: 3
tom: 8
mary: 2
The error comes from this line:
if(exists $index{$index->{USER}})
The $ sigil in Perl 5 with {} after the name means that you are getting a scalar value out of a hash. There is no hash declared by the name %index. I think that you probably just need to add a -> operator so the problem line becomes:
if(exists $index->{$index->{USER}})
but not having the data makes me unsure.
Also, good on you for using use strict or you would be instantiating the %index hash silently and wondering why your results didn't make any sense.
my %total;
for my $name_pages_pair (#sorted_users) {
$total{$name_pages_pair->{USER}} += $name_pages_pair->{PAGES};
}
for my $username (sort keys %total) {
printf "%20s %6u\n", $username, $total{$username};
}
I am trying to create a script to generate a csv file with the results of some ldap queries using Net::LDAP but I'm having troubles skipping incomplete lines if one element of the #attributes array is blank.
my #attributes = ('cn', 'mail', 'telephoneNumber');
So for example, if a user has no mail listed, or no telephoneNumber listed, then it should skip the hold field instead of returning:
"Foo Bar",, # this line should be skipped since there is no mail nor telephone
"Bar Foo","bar#foo.com", # this line should be skipped too, no number listed
"John Dever","john_dever#google.com","12345657" # this one is fine, has all values
My loop right now is looking like this:
# Now dump all found entries
while (my $entry = $mesg->shift_entry()){
# Retrieve each fields value and print it
# if attr is multivalued, separate each value
my $current_line = ""; # prepare fresh line
foreach my $a (#attributes) {
if ($entry->exists($a)) {
my $attr = $entry->get_value($a, 'asref' => 1);
my #values = #$attr;
my $val_str = "";
if (!$singleval) {
# retrieve all values and separate them via $mvsep
foreach my $val (#values) {
if ($val eq "") { print "empty"; }
$val_str = "$val_str$val$mvsep"; # add all values to field
}
$val_str =~ s/\Q$mvsep\E$//; # eat last MV-Separator
} else {
$val_str = shift(#values); # user wants only the first value
}
$current_line .= $fieldquot.$val_str.$fieldquot; # add field data to current line
}
$current_line .= $fieldsep; # close field and add to current line
}
$current_line =~ s/\Q$fieldsep\E$//; # eat last $fieldsep
print "$current_line\n"; # print line
}
I have tried code like :
if ($attr == "") { next; }
if (length($attr) == 0) { next; }
and several others without any luck. I also tried simple if () { print "isempty"; } debug tests and its not working. Im not exacly sure how could I do this.
I appreciate any help or pointers you could give me on what am I doing wrong.
Thanks a lot in advance for your help.
UPDATE:
Per chaos request:
my $singleval = 0;
A sample run for this program would return:
Jonathan Hill,Johnathan_Hill#example.com,7883
John Williams,John_Williams#example.com,3453
Template OAP,,
Test Account,,
Template Contracts,,
So what I want to do is to skip all the lines that are missing a field, either email or extension number.
Label your while loop:
Record: while (my $entry = $mesg->shift_entry()){
and use:
next Record;
Your problem is that your next is associated with your foreach. Using the label avoids that.
By the way, $attr == '', though it will work in this case, is bad logic; in perl, == is a numeric comparison. String comparison would be $attr eq ''. Though I'd just use next Record unless $attr.