Converting a string to a filehandle #2

Hello

I'm processing a file of test data that looks something like:

FH1,data1,data2,data3,...etc
FH2,data1,data2,data3,...etc
FH1,data1,data2,data3,...etc

Each line split into an array and processed.

The first element (FH1, FH2, etc) is the name of the filehandle the
output should be printed to.

I'm trying to do something like:

use strict;
use warnings;

open (FH1, ">file1");
open (FH2, ">file2");

open (INPUT, "<inputfile");

while (<INPUT>)
{
....split line
....process data
....create output

  my $FH =3D $split_line[0]

  print $FH "$output\n";

}

But I get the error:
"Can't use string ("FH1") as a symbol ref while "strict refs" in use at
my_script.pl line 387, <INPUT> line 1."

I can get round it without too much difficulty with an if statement, but
I was wondering if there was a simple way to turn a string into a
filehandle.  I've tried various things like:

my $FH =3D "\*$split_line[0]";
or=20
print \*$FH "$output\n";
or
changing the data to hold \*FH1 in the first field.

All to no avail.

The closest thing I've found is the following from the perldocs website:

	$fh =3D   SOME_FH;       # bareword is strict-subs hostile
	$fh =3D  "SOME_FH";      # strict-refs hostile; same package only
	$fh =3D  *SOME_FH;       # typeglob
	$fh =3D \*SOME_FH;       # ref to typeglob (bless-able)
	$fh =3D  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH
typeglob

But I don't think that answers my question (or if it does, I'm too dumb
to see that answer...)

Can anyone point me in the right direction?

Cheers
Andy                                                              =20

Capgemini is a trading name used by the Capgemini Group of companies =
which includes Capgemini UK plc, a company registered in England and =
Wales (number 943935) whose registered office is at No. 1 Forge End, =
Woking, Surrey, GU21 6DB.
This message contains information that may be privileged or confidential =
and is the property of the Capgemini Group. It is intended only for the =
person to whom it is addressed. If you are not the intended recipient, =
you are not authorized to read, print, retain, copy, disseminate, =
distribute, or use this message or any part thereof. If you receive this =
message in error, please notify the sender immediately and delete all =
copies of this message.

0
Andrew
2/9/2009 12:41:07 PM
perl.beginners 29388 articles. 4 followers. Follow

2 Replies
342 Views

Similar Articles

[PageSpeed] 46

Taylor, Andrew (ASPIRE) <Andrew.Taylor2@hmrcaspire.com> wrote:
> I'm processing a file of test data that looks something like:
>=20
> FH1,data1,data2,data3,...etc
> FH2,data1,data2,data3,...etc
> FH1,data1,data2,data3,...etc
>=20
> Each line split into an array and processed.
>=20
> The first element (FH1, FH2, etc) is the name of the filehandle the
> output should be printed to.
[...]

Try

my %fh;

open( $fh{'FH1'}, '>', $somefile ) or die "Can't open $somefile: $!";
....

print $fh{'FH1'} "$output\n";

HTH,
Thomas
0
t
2/9/2009 1:16:44 PM
On Mon, Feb 09, 2009 at 12:41:07PM -0000, Taylor, Andrew (ASPIRE) wrote:
> Hello
> 
> I'm processing a file of test data that looks something like:
> 
> FH1,data1,data2,data3,...etc
> FH2,data1,data2,data3,...etc
> FH1,data1,data2,data3,...etc
> 
> Each line split into an array and processed.
> 
> The first element (FH1, FH2, etc) is the name of the filehandle the
> output should be printed to.
> 
> I'm trying to do something like:
> 
> use strict;
> use warnings;
> 
> open (FH1, ">file1");
> open (FH2, ">file2");
> 
> open (INPUT, "<inputfile");
> 
> while (<INPUT>)
> {
> ...split line
> ...process data
> ...create output
> 
>   my $FH = $split_line[0]
> 
>   print $FH "$output\n";
> 
> }
> 
> But I get the error:
> "Can't use string ("FH1") as a symbol ref while "strict refs" in use at
> my_script.pl line 387, <INPUT> line 1."

You are using "strict refs", which is a good idea in general.  But then
you are trying to use a symbolic ref, which you explicitly said you
wouldn't do.

The solution therefore, is to allow symbolic refs where you are trying
to use them.  This can be done by placing <no strict "refs";> just above
your print statement.

> The closest thing I've found is the following from the perldocs website:
> 
> 	$fh =   SOME_FH;       # bareword is strict-subs hostile
> 	$fh =  "SOME_FH";      # strict-refs hostile; same package only
> 	$fh =  *SOME_FH;       # typeglob
> 	$fh = \*SOME_FH;       # ref to typeglob (bless-able)
> 	$fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH
> typeglob
> 
> But I don't think that answers my question (or if it does, I'm too dumb
> to see that answer...)

The clue is on the second line.

The whole thing does seem a little fragile though, with such a tight
connection between the internals of your program and the data in your
file.

-- 
Paul Johnson - paul@pjcj.net
http://www.pjcj.net
0
paul
2/9/2009 4:00:26 PM
Reply:

Similar Artilces:

Converting a string to a filehandle
Dear expert, Is there a way to do it? Module for it? Suppose I have this large string. my $string = 'foo bar qux woo etc etc'; I would like to convert that string as if it is stored inside a file, and bypassing the file creation step. For example, my $filehandle = do_sth_to_convert($string); Such that I can straight away do things like: while (<$file_handle>) { print; } [download] Regards, Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This emai...

convert to string #2
i want to convert to string an integer value which i'm receving from database, in an SqlDataReader, how to do this?SHASHANK BHIDECAPGEMINI INDIA"THE ROAD TO SUCCESS IS ALWAYS UNDER CONSTRUCTION MARK MY RESPONSE AS ANSWER TO HELP ME BUILD IT :)"  you can use the toString() function.. for e.g. objreader["columnname"].toString() The real voyage of discovery consists not in making new landscapes, but in having new eyes shashankgwl:i want to convert to string an integer value which i'm receving from database, in an SqlDataReader, how to do this? Hi,...

string to string[] #2
string[] strArray;while(dtardrUsrDet.Read())   {string strUsrEmail=dtardrUsrDet.GetValue(0).ToString(); int intDayDiff=System.Convert.ToInt16(dtardrUsrDet.GetValue(1).ToString());if(intDayDiff==45) {   strArray=strUsrEmail; }if(intDayDiff==30) {   strArray=strUsrEmail; }     how to store string values from reader into string arrayMark As Answer If my reply helped you. Hi, I am assuming that you want each string in an array, not each character as a separate string in a string array here.... The easiest way is to create an ArrayList, add each stri...

converting string to datetime #2
 HiI'm using a form where the user enters 2 dates using cylinder, i have a column where i have to calculate difference between 2 dates, I got a code to compare 2 dates but now the problem is that I'm storing the date in a text box, so i use string to access it but how can i compare using string, i need to know how to assign or convert string date to date time object.Thanks in advance Use: Convert.ToDateTime(strDate) Convert.ToDateTime(string DateTime) Sruthish: i need to know how to assign or convert string date to date time object. Or DateTime mydate=(DateTime)Y...

Convert String to Integer #2
Hello, I'm retrieving the value of a textbox from a data grid. However, I need to insert this value into a DB into a field that is classified as integer. I receive an error saying it can't be converted to integer. Here is my code: Public Sub testgrid_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Dim DataID As Integer = CType(DataGrid1.DataKeys(e.Item.ItemIndex), Integer) Dim qtyText As Textbox = CType(e.Item.Cells(4).Controls(1), Textbox) Dim qty As String = qtyText.Text I...

convert string to datetime #2
 hi , i want to convert a string "ddMMyy" to datetime i tried  DateTime dt =DateTime.ParseExact( "121299", "ddMMyy", null) but i doesn't work !!! i got this error : String was not recognized as a valid DateTime.any ideas?? This works in me:  protected void Page_Load(object sender, EventArgs e) { string sDate = "121299"; string format = "ddMMyy"; DateTime datetime = DateTime.ParseExact(sDate, format, null); Response.Write(datetime.ToShortDateString()); }  Reg...

Converting string to int #2
hi all!  is there a way to do that? or a way to get the value of a dropdown list as an int? do forgive my bad spelling Given a string variable s, use either int i = Convert.ToInt32( s ); or int i = Int32.Parse( s ); You can also use Int32.TryParse() as well.RegardsDave Hi, use method Int32.Parse(string) or Int32.TryParse(string, out int). For example:int id = 0; if (int.TryParse(Request.QueryString["id"], out id) { // do something } else { // fix problem } Have a nice day, R.rjichaprogrammer + caffeine + taurine = new application mestrebisli : ...

How to convert String to DateTime #2
HI, I am storing the string like MM-DD-YYYY using textbox .How can i convert it inot DateTime, Can any one help me on this.... :--(Thanks,Pavan. Convert.ToDateTime(TextBox1.Text)DateTime.Parse(TextBox1.Text) We All move to our original place.Don't forget.Imran Baloch Hi,    You can convert that text as                        string date = ConvertTo.DataTime(TextBox.Text).ToString();             &nbs...

convert string to date #2
I am running pb9 Why this coversion does not work? I got '01/01/1900' for ld. I want ld to hold '01/02/2010' Please help date ld string lsdt lsdt = '01/02/2010 00:00:00' ld = date(lsdt) TIA Date() is dependent on system settings, so it could be that your system isn't set to something ending with a year. For example, '1/2/2010' works on my system, but '2010/1/2' doesn't; the reverse may be true on your system. (And, yes this dependency sucks and that there isn't a native way to control this, beyond writing your own Power...

Convert String to XML #2
hi,     I write a xml data in webform like xmlformat using response.write(server.htmlencode(ds.getxml()) //where ds is a Dataset   afterwards i am reading the xml data in webform using ............  objWReq = HttpWebRequest.Create(url) objWResp = objWReq.GetResponse Dim stream As IO.Stream = objWResp.GetResponseStream Dim reader As New IO.StreamReader(stream)  Dim data As String = reader.ReadToEnd//data it should be in  XML *** String Format  reader.Close() stream.Close() in data variable the format is like that...

convert string to date #2
how do i convert a string in a textbox to a date using C#? eg. i have 09/05/2008 as input into a textbox.....how do i convert it to a date?i have dateStart = Convert.ToDateTime(TextBoxStart.Text.Trim()); which gives an error saying the string cannot be converted to datetime.....but it is in this exact format: dd/mm/yyyy...i just need to convert the string to check if its less than another date DateTime.Parse(...) Hope that helps.  DateTime dt = Convert.ToDateTime(TextBoxStart.Text); Tested as shown below: Console.WriteLine("Time is {0}", dt); //OutPut...

convert string to int #2
Hi, i try to return cateogyid its integer type  but it shows the error Cannot implicitly convert type 'string' to 'int' i have send the coding step1  i have created procedure called addcategoryproc and i created class called categorycls to call the procedurepublic string addcat(string categorynames) {SqlConnection myconnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);SqlCommand myCommand = new SqlCommand("addcategoryproc",myconnection); myCommand.CommandType = CommandType.StoredProcedure; myCommand.Param...

Convert string to number #2
Hey all, I have got a text field in the summary band in a report datawindow which I want to set to a value at runtime and the value will come from the user. The value will be used for further addition and substraction. How do I convert this value from a string to a number? Thanks in advance for any help. Jian Kuang Depending on the scale or type of number, you can use Dec ( ), Long ( ), Double ( ), Real ( ), or Integer ( ). All of them call for a string or blob argument. Jian Kuang <jkuang@vitinc.com> wrote in message news:3757DC4F.41131683@vitinc.com... Hey a...

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...

Web resources about - Converting a string to a filehandle #2 - 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: 12/25/2015 1:24:40 PM