converting arrayname to string or vice-versa

Hi,
This one is puzzling me. 
I know it's in the faq, to not use variables for variable naming,
but I find it odd that I can't get a "stringified" form of a variable
name, maybe from the symbol table? Or from the B line of modules?

Say I have an array like:

@somename = (1,2,3,4,5);

and I want to write that array to a file, but I
want the file named automatically by just
dropping the @ off of the @somename.
How would you go about doing it? Plus,
I would like to be using strict.

Also the reverse: take a filename like "somename"
and load it to an array @somename just by some
concantation like @{'somename'}.

The @{'somename'} seems to work, but not with strict.

It seems like it should be easy, but it's not.


0
zentara
6/2/2003 11:53:06 AM
perl.beginners 29388 articles. 4 followers. Follow

5 Replies
868 Views

Similar Articles

[PageSpeed] 34
Get it on Google Play
Get it on Apple App Store

On Mon, Jun 02, 2003 at 07:53:06AM -0400 zentara wrote:

> This one is puzzling me. 
> I know it's in the faq, to not use variables for variable naming,
> but I find it odd that I can't get a "stringified" form of a variable
> name, maybe from the symbol table? Or from the B line of modules?
> 
> Say I have an array like:
> 
> @somename = (1,2,3,4,5);
> 
> and I want to write that array to a file, but I
> want the file named automatically by just
> dropping the @ off of the @somename.
> How would you go about doing it? Plus,
> I would like to be using strict.

This can be done, even with strictures enabled. @somename has an entry
in the symbol-table if it is a package variable. The entry looks like

    'somename' => *::somename,

So under the key 'somename' you have a glob as corresponding value. A
glob has several slots, one of them the ARRAY slot which you will
automatically get when you use @{ } for dereferencing:

    use strict;
    @main::somename = qw(a b c);
    ...
    # and now get the content of @somename
    my @values = @{ $::{somename} };

I think from that it should be obvious how you store it in a file
[untested]:

    for my $var ( qw/array1 array2/ ) {
        my @values = @{ $::{ $var } };
        my $valstring = join "," @values;
        print FILE "\@main::$var = ($valstring)\n";
    }

You will have to take additional care if your variables don't contain
plain numbers. If they contain strings, you can't just join with
commatas. You then also have to enclose them in quotes. Also, I am
storing a string like

    @main::array1 = (1,2,3);

because it can later just be evaled (or do()ne) under strictures.

> Also the reverse: take a filename like "somename"
> and load it to an array @somename just by some
> concantation like @{'somename'}.

If you store it similarily to the above, a plain

    do 'somename';

should do.

> The @{'somename'} seems to work, but not with strict.

No, because it's a symbolic reference. The @{ *glob } trick is slightly
different in that you don't dereference a string.

> It seems like it should be easy, but it's not.

It's not so hard with a little bit of understanding for the
symbol-table. However, and that's the limitation, you can't thusly store
lexical (my()-) variables because they don't have an entry in the
symbol-table. In this case you need to walk the pads of the Perl
interpreter which one of the B:: modules could indeed help you with.

Tassilo
-- 
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval

0
tassilo
6/2/2003 12:28:01 PM
zentara wrote:
> Hi,
> This one is puzzling me.
> I know it's in the faq, to not use variables for variable naming,
> but I find it odd that I can't get a "stringified" form of a variable
> name, maybe from the symbol table? Or from the B line of modules?
> 
> Say I have an array like:
> 
> @somename = (1,2,3,4,5);
> 
> and I want to write that array to a file, but I
> want the file named automatically by just
> dropping the @ off of the @somename.
> How would you go about doing it? Plus,
> I would like to be using strict.

I don't understand this part. Any techinique for accessing the "stringified"
form of the variable name would require using that very string as input no?
What do you need to do other than the following?

   my $filename = "somename.dat";

If the question is "How do I find the names of all the arrays in a
package?", then you probably shouldn't be using package variables for this.
Use a hash to hold those arrays instead.

> 
> Also the reverse: take a filename like "somename"
> and load it to an array @somename just by some
> concantation like @{'somename'}.
> 
> The @{'somename'} seems to work, but not with strict.

This is the thing the FAQ says not to do. Just don't do it. Use a hash.

Consider: what if the filename is "INC"? Do you want to trash @INC?
0
Bob_Showalter
6/2/2003 1:28:11 PM
On Monday, June 2, 2003, at 06:53  AM, zentara wrote:

> Say I have an array like:
>
> @somename = (1,2,3,4,5);
>
> and I want to write that array to a file, but I
> want the file named automatically by just
> dropping the @ off of the @somename.
> How would you go about doing it?

Well, if your still inside your code, you know the name of the 
variable, right?  Couldn't you just create a file named 'somename'?  
You typed it once to name the variable, seems like you could type it 
again to name the file.

> Also the reverse: take a filename like "somename"
> and load it to an array @somename just by some
> concantation like @{'somename'}.
>
> The @{'somename'} seems to work, but not with strict.

If you dump it out using something like:

perl -MData::Dumper -e 'print Data::Dumper->Dump([[1..5]], 
["*somename"]), "\n";'

You could simply do 'path/to/something.pl'; to get it back, I believe.  
This shouldn't upset strict.

However, this, to me, is a textbook perfect example of why the 
statement, "Always use strict," is patently false.  The strict pragma 
is three tools in one, but you may not need all of those tools all the 
time.  Does your dentist use a drill every time they clean your teeth?  
If Perl supports a feature and you aren't using it because strict would 
complain, that's just silly.  You turned it on in the first place, 
remember?

use strict; # ask Perl to keep us honest

# and then later...

{ # localize our rules change here
	no strict 'refs'; # tell Perl, I know what I'm doing here, so stay out 
of my way
	# something including your @{'somename'} construct
} # scope ends and strict is back in business

Never feel bad about changing the rules, as long as you understand why 
you are changing them.

James

0
james
6/2/2003 1:32:39 PM
Tassilo Von Parseval wrote:
> On Mon, Jun 02, 2003 at 07:53:06AM -0400 zentara wrote:
>
> > This one is puzzling me.
> > I know it's in the faq, to not use variables for variable naming,
> > but I find it odd that I can't get a "stringified" form of a
> > variable name, maybe from the symbol table? Or from the B line of
> > modules?
> >
> > Say I have an array like:
> >
> > @somename = (1,2,3,4,5);
> >
> > and I want to write that array to a file, but I
> > want the file named automatically by just
> > dropping the @ off of the @somename.
> > How would you go about doing it? Plus,
> > I would like to be using strict.
>
> This can be done, even with strictures enabled. @somename has an
> entry in the symbol-table if it is a package variable. The entry
> looks like
>
>     'somename' => *::somename,
>
> So under the key 'somename' you have a glob as corresponding value.
> A glob has several slots, one of them the ARRAY slot which you will
> automatically get when you use @{ } for dereferencing:
>
>     use strict;
>     @main::somename = qw(a b c);
>     ...
>     # and now get the content of @somename
>     my @values = @{ $::{somename} };
>
> I think from that it should be obvious how you store it in a file
> [untested]:
>
>     for my $var ( qw/array1 array2/ ) {
>         my @values = @{ $::{ $var } };
>         my $valstring = join "," @values;
>         print FILE "\@main::$var = ($valstring)\n";
>     }
>

But very few people will understand how this works and, worse,
what it is doing. Far better, I think is

  my @values = do { no strict 'vars'; @$var };

Rob



0
rob
6/2/2003 3:57:51 PM
Rob Dixon wrote:
> Tassilo Von Parseval wrote:
> > On Mon, Jun 02, 2003 at 07:53:06AM -0400 zentara wrote:
> >
> > > This one is puzzling me.
> > > I know it's in the faq, to not use variables for variable
> > > naming, but I find it odd that I can't get a "stringified" form
> > > of a variable name, maybe from the symbol table? Or from the B
> > > line of modules?
> > >
> > > Say I have an array like:
> > >
> > > @somename = (1,2,3,4,5);
> > >
> > > and I want to write that array to a file, but I
> > > want the file named automatically by just
> > > dropping the @ off of the @somename.
> > > How would you go about doing it? Plus,
> > > I would like to be using strict.
> >
> > This can be done, even with strictures enabled. @somename has an
> > entry in the symbol-table if it is a package variable. The entry
> > looks like
> >
> >     'somename' => *::somename,
> >
> > So under the key 'somename' you have a glob as corresponding
> > value. A glob has several slots, one of them the ARRAY slot which
> > you will automatically get when you use @{ } for dereferencing:
> >
> >     use strict;
> >     @main::somename = qw(a b c);
> >     ...
> >     # and now get the content of @somename
> >     my @values = @{ $::{somename} };
> >
> > I think from that it should be obvious how you store it in a file
> > [untested]:
> >
> >     for my $var ( qw/array1 array2/ ) {
> >         my @values = @{ $::{ $var } };
> >         my $valstring = join "," @values;
> >         print FILE "\@main::$var = ($valstring)\n";
> >     }
> >
>
> But very few people will understand how this works and, worse,
> what it is doing. Far better, I think is
>
>   my @values = do { no strict 'vars'; @$var };

Apologies, that'll be

  my @values = do { no strict 'refs'; @$var };

Rob





0
rob
6/2/2003 4:01:19 PM
Reply:

Similar Artilces:

String ccomparison problem. How to convert AUTF8String (nsACString) to a regular String or vice versa
Hi, I'm having trouble comparing strings of different types in Java Script The two strings are equal when displayed in an alert popup but the "==" condition fails The two types are the following 1. nsIURI.spec http://developer.mozilla.org/en/docs/nsIURI#Attributes and 2. http://developer.mozilla.org/en/docs/nsIScriptableInputStream:read i receive a URL through nsIScriptableInputStream.read() and attempt to compare it with nsIURI.spec In this sample code, i pass in the nsIScriptableInputStream.read() as the "url" parameter, which is then compa...

Convert String into byte and vice versa
Hi, I want to know how can i convert byte array into string and then that string again back to the same equivalent byte array. I tried this: string str = Convert.ToBase64String(cipherText); byte[] sampleVar = Encoding.ASCII.GetBytes(str); But it seems that sampleVar is not equivalent to cipherText which is actually of the type byte[] :(. Any help... I am actually using the thing in TDES encryption where i have cipherText stored as string then i load it to string variable and need to convert it nto byte array again .. but it gives bad data. If i dont do the conversion ......

Convert from string to integer and vice versa
I’m new to Visual Basic and am developing my first web application with VB. It’s based on at skeleton script from my host provider. It’s a form where users fill in some data, which I validate with the VB script, before the data are sent with an e-mail. I’ve mostly been able to turn the skeleton script into an application which suits my needs, but I’ve run into some problems with code which should be trivial. I need to convert from string to integer and vice versa. I’ve been searching the web, and this forum, for information on how to do this. I’ve found several ways to convert...

Converting a list of string into string
When I try the following code in Prism I get the error "Error 8 (CE15) Type mismatch, cannot assign array of System.String to System.String " ***************************************************************** var mobileNumberList :List<string> mobNumberArray :string Begin mobileNumberList.add('1234567890'); mobNumberArray := mobileNumberList.ToArray();//error here end; *************************************************************** What needs to be done to convert an array of strings to a string Venkatesh Venkatesh VT a écrit : > When I...

convert octet string to string
I'm trying to use IDM 3.5.1 provision an AD environmnet with users from eDir. We wanna provision as much info as possible, but one attribute gives us headaches. This is an auxiliary attribute associated with each user in eDir that has it's syntax set to octet string. Problem is we need to provision this over to another attribute in AD that uses string as its syntax. Is thee a way through XPath or ECMA script to have the value converted during the provisioning? I've no experience with either XPath or ECMA so please be detailed in your replies. Thx -- jdoeconsu...

How to Convert SQL Server into into XML and Vice-versa
HiiI want to Convert the given SQL Table into XML Format and again convert that XMl into the Table Format.While Converting i want to make Validation also.Basically i want to make Transfer from one Database to another using XML as a Mediium.Is it possible to implement if yes then do help me out.    Thanks and Regard,Pawan choure Retrieving Data as XML from SQL Server -http://www.sitepoint.com/article/data-as-xml-sql-server/ Import - http://support.microsoft.com/kb/316005  If I was helpful, please mark "answered" so I can get credit. Thanks!  Thank...

Convert string to string array.
Hi, We have a string array argument in datawindow object for 'IN' sql statement. Our user enter a string in a single line edit. How to convert the string to a string array for the argument of datawindow? ex. user input : 'A', 'B', 'C' => str_arr[]={'A', 'B', 'C'} dw_1.retrieve(str_arr) Thanks in advance. Take a look at the n_cst_string object in the pfc. It has a method called of_ParseToArray that does exactly what you're looking for. It's a pretty simple task to 'port' the code ...

converting inches to powerbuilder units and vice-versa
Hi All, Can anyone tell me how to convert inches to PBUs/ PBUs to inches. The reason is that I have datawindows with margins set in 1/1000 inches and I need them converted to PBUs. Thanks in advance, Ivan ...

How to convert a String into a UTF8 String
Hello! I want to convert a normal String into a UTF8 String for example:myString = BüromyUTF8String = Büros  I dont know how to do this. In PHP you can do this with myUTF8String = utf8_encode(myString) Thank you for all hints! try this string test ="ÁÉÍÓÚ áéíóú àèìòù äëïöü Ññ €"; byte[] a= System.Text.Encoding.UTF8.GetBytes(test); string test2= System.Text.Encoding.UTF8.GetString(a);  greetingsBest Regards,Sebastián DopicoBlog Desarrollador Thank you Sebastián! If I make it like that - test2 looks the same as test.But I think my problem is solved. (Someone tol...

How to store XMLDocument file into string variable and vice versa
I have to create DLL file in which I will have to use one property as follows private string pXML;public string XML{get { return pXML; }set { pXML = value; }} the property input(mean set) will be XML content (but type of property is string) and output(mean get) will be string.  How to code the above scenario.    You can try string xmlread = "<root><child>Child 1</child><child>Child 2</child></root>";XmlDocument xml = new XmlDocument();xml.LoadXml(xmlread);XML=xml.InnerXml;  Marking a Rep...

Converting Tbird to Windows Mail & vice versa
Name: Dennis O'Flynn Email: d_oflynnatbigponddotcomdotau Product: Thunderbird Summary: Converting Tbird to Windows Mail & vice versa Comments: Recently used IMAPSize to convert Thunderbird mailboxes to Windows Mail. Happy with Tbird but nedded to convert. Worked well. including attachments. Would recommend. regards Dennis Browser Details: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 From URL: http://hendrix.mozilla.org/ Note to readers: Hendrix gives no expectation of a response to this feedback but if ...

Convert Date from Gregorian to Hijri (Arabic) and vice versa
I am using PB 11.5.1 and ASA 11 How can I convert Date from Gregorian to Hijri(arabic date) and vice versa. If there is DLL or ActiveX or Formula to do that please provide me with the link Thanks ...

Component that can converts HTML to RTF(TRichEdit) and vice versa?
Hi, All Is there any component out there that can converts HTML to RTF (TRichEdit) and vice versa? Thanks William On 2012-07-30 18:47:56 -0400, William Yu <> said: > Hi, All > > Is there any component out there that can converts HTML to RTF > (TRichEdit) and vice versa? ScroogeXHTML can convert RTF to HTML, but I don't believe that it can do the reverse. Still, you may find it useful. http://www.habarisoft.com/scroogexhtml_delphi.html -- Kevin Powick William WPTools does but its a) expensive b) a full word processor Roy Lambert ...

Convert UPPERCASE string to Upper-Lower Case (ie. THIS IS MY STRING -> This Is My String)
I recently had the need to convert an all capitalized string to upper/lower case, but couldn't find anything to do it in XSLT 1.0.  If it helps anyone out, I wrote the following:   Call it using: <xsl:template match="Ads">  <xsl:call-template name="ToUpperLowerCase">   <xsl:with-param name="inputString" select="YOURSTRINGHERE"/>   <xsl:with-param name="index" select="0"/>   <xsl:with-param name="loopCount" select="st...

Web resources about - converting arrayname to string or vice-versa - perl.beginners

Facebook Begins Converting Users To HTTPS
Are you willing to sacrifice a little bit of speed for a lot more safety? Facebook is asking that very question with its announcement that it ...

Facebook No Longer Converting Groups Into Pages
Back when Facebook first launched Facebook Pages, many businesses and brands who had built up substantial audiences in their Facebook Groups ...

Vert - simply converting for iPhone, iPad, and iPod touch on the iTunes App Store
Get Vert - simply converting on the App Store. See screenshots and ratings, and read customer reviews.

Converting SIM Card to Micro SIM Card - Flickr - Photo Sharing!
Place new Micro SIM into the iPhone SIM card tray

Ayaan Hirsi Ali on Converting Muslims to Christianity - YouTube
Complete video at: http://fora.tv/2010/07/29/Nomad_From_Islam_to_America_with_Ayaan_Hirsi_Ali Ayaan Hirsi Ali explains her support of missionary ...

Click go fears of converting print files
Is there a way to convert a print queue item to a .RTF or .PDF file? I like to save or email them. - The Sydney Morning Herald

Sudanese woman ordered to hang under sharia law for converting to Christianity gives birth
Khartoum, Sudan: A Christian Sudanese woman sentenced to hang for apostasy has given birth in jail, a Western diplomat said on Tuesday.

Imams warn against radicalism to Aboriginal inmates converting to Islam
The prison system has enlisted the help of ASIO to crack down on radicalisation behind bars amid revelations that Aboriginals are converting ...

Converting the world's companies one by one - The Science Show - ABC Radio National (Australian Broadcasting ...
Image: Trucks carrying logs make their way up a road in Jambi, Indonesia. A vast area of the Sumatran forest, and orangutan habitat, is being ...

Converting Churches Into Homes Is The Latest Hollywood Trend
You don't have to be a believer to be moved by the beauty of a church.

Resources last updated: 11/26/2015 5:10:53 PM